類變量和對象變量


  • 先上代碼:
class Man():
    #直接定義的類的變量,屬於類   
    #其中 gender, avg_height為基本數據類型,immutable
    #lis為列表類型,為mutable的
    gender = 'male'   
    avg_height = 1.75
    lis = ['hello', 'world']

    def __init__(self, name):
        self.name = name  #name在類的構造函數中定義,是屬於對象的變量

a = Man('jason')
b = Man('tom')
 
#通過一個對象a訪問一個變量x,變量的查找過程是這樣的:
#先在對象自身的__dict__中查找是否有x,如果有則返回,否則進入對象a所屬的類A的
#__dict__中進行查找
 
#對象a試圖修改一個屬於類的 immutable的變量,則python會在內存中為對象a
#新建一個gender變量,此時a就具有了屬於自己的gender變量
a.gender = 'female'

#對象b直接調用給類變量進行Man.lis賦值等容易認為新建對象的方法,會直接給對象b新建這個對象
b.lis = ['olleh', 'world']
#若為append等建立在已有對象的基礎上的方法則會去修改類變量
#b.lis.append('new')
#print ('a.lis',a.lis)
#print ('b.lis',b.lis) 
#print('class.lis:',Man.lis)

#可用對象的.__class__方法找到對象的類,然后修改類變量
a.__class__.lis = ['hello', 'dlrow']

Man.t = 'test' #此時Man的變量又多了t,但是對象a和b中沒有變量t。
a.addr = '182.109.23.1' #給對象a定義一個變量,對象b和類Man中都不會出現

print ('a:dict',a.__dict__) #屬於a的變量,有 name, gender, addr
print ('b:dict',b.__dict__)  #屬於b的變量,只有name
print ('class man dict:',Man.__dict__) #屬於類Man的變量,有 gender,avg_height,lis,但是不包括 name
#name是屬於對象的變量 
 
print ('a.gender:',a.gender)  #female
print ('b.gender:',b.gender)  #male
 
print ('a.lis',a.lis) #['hello', 'dlrow']
print ('b.lis',b.lis) #['olleh', 'world']
print('class.lis:',Man.lis)#['hello', 'dlrow']

output:

a:dict {'name': 'jason', 'gender': 'female', 'addr': '182.109.23.1'}
b:dict {'name': 'tom', 'lis': ['olleh', 'world']}
class man dict: {'__module__': '__main__', 'gender': 'male', 'avg_height': 1.75, 'lis': ['hello', 'dlrow'], '__init__': <function Man.__init__ at 0x7f1f39f23bf8>, '__dict__': <attribute '__dict__' of 'Man' objects>, '__weakref__': <attribute '__weakref__' of 'Man' objects>, '__doc__': None, 't': 'test'}
a.gender: female
b.gender: male
a.lis ['hello', 'dlrow']
b.lis ['olleh', 'world']
class.lis: ['hello', 'dlrow']

簡單說,類變量就是在類中而非方法中定義的變量,是每個對象共有的,有點像C++中static修飾的靜態屬性.
對象變量就是在方法中定義的變量,是每個對象特有的,各有各的值.

未完待續...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM