Python的類變數和成員變數以及區域性變數
阿新 • • 發佈:2019-02-17
Python的類變數可以通過類和例項名字進行訪問而成員變數只能通過例項名來訪問,區域性變數只能在方法體內被使用。
http://blog.csdn.net/lc_910927/article/details/38757363
類變數和成員變數雖然名字相同但是儲存的地址不是相同的。
# -*- coding: utf-8 -*-
class A():
privatestring="aa"
def __init__(self,value,privatevalue):
self.name=value
self.privatestring=privatevalue
def change_privatestring(value):
A.privatestring=value
AAA=A("AA","BB")
print(A.privatestring)
print(AAA.privatestring)
print(A.change_privatestring("CCC"))
print(A.privatestring)
print(AAA.privatestring)
print(A.__dict__)
print(AAA.__dict__)
輸出結果:
/usr/bin/python3.5 /home/liusenubuntu/PycharmProjects/sentence/segment/privatelearn.py
aa
BB
None
CCC
BB
{'__module__' : '__main__', '__init__': <function A.__init__ at 0x7fb1fefad8c8>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__dict__': <attribute '__dict__' of 'A' objects>, 'change_privatestring': <function A.change_privatestring at 0x7fb1fefadae8>, 'privatestring': 'CCC', '__doc__' : None}
----------------------
{'name': 'AA', 'privatestring': 'BB'}
Process finished with exit code 0
類變數是全域性變數,一次修改,所有例項化物件的值全部修改
跟Java進行對比:
package classlearn;
public class Node {
public static int a=1;
}
package classlearn;
public class TestNode {
public static void main(String[] args) {
Node nodeA=new Node();
nodeA.a=2;
System.out.println(nodeA.a);
Node nodeB=new Node();
System.out.println(nodeB.a);
Node nodeC=new Node();
System.out.println(nodeC.a);
}
}
實驗結果:
2
2
2
# -*- coding: utf-8 -*-
class A():
privatestring="aa"
def __init__(self,value):
self.name=value
def change_privatestring(value):
A.privatestring=value
AAA=A("AA")
print(A.privatestring)
print(AAA.privatestring)
BBB=A("BB")
A.change_privatestring("BBB")
print(A.privatestring)
print(AAA.privatestring)
print(BBB.privatestring)
print(AAA.change_privatestring("CCC"))
輸出結果:
/usr/bin/python3.5 /home/liusenubuntu/PycharmProjects/sentence/segment/privatelearntwo.py
aa
aa
BBB
BBB
BBB
Traceback (most recent call last):
File "/home/liusenubuntu/PycharmProjects/sentence/segment/privatelearntwo.py", line 16, in <module>
print(AAA.change_privatestring("CCC"))
TypeError: change_privatestring() takes 1 positional argument but 2 were given
Process finished with exit code 1
普通方法不能被例項化物件呼叫。