類變數和物件變數
阿新 • • 發佈:2018-11-20
- 先上程式碼:
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']