python中類方法與類屬性示例
阿新 • • 發佈:2019-02-14
#coding=utf-8 class Animal(object): def __init__(self,name ='動物',color ='白色'): self.name =name self.color = color class horse(Animal): def __init__(self,name): super().__init__(name) bailongma = horse("白龍馬") print(bailongma.color) print(bailongma.name) class People(object): address = '中國' #類屬性 #例項方法 def __init__(self): self.name = 'xiaohai'#例項屬性 self.age = 8#例項屬性 #例項方法 def setAddress(self): self.address = 'America' #類方法 @classmethod def setNewAddress(self): self.address = 'UA' xiaohai = People() print(xiaohai.address) #中國 xiaohai.setAddress() print(People.address) #中國 print(xiaohai.address) #America xiaohai.setNewAddress() print(People.address) #UA print(xiaohai.age) print(xiaohai.name) ''' 總結: 類物件可以呼叫類方法(如 People.setNewAddress())和類屬性(People.address),但是不能呼叫例項方法(People.setAddress()),也不能訪問類屬性(People.name()) 例項物件可以呼叫類方法(xiaohai.setNewAddress())和例項方法(xiaohai.setAddress()),也可以獲取類屬性(xiaohai.address)和例項屬性(xiaohai.name),但只能修改例項屬性(xiaohai.age=9)不能修改類屬性(xiaohai.address='us'(這裡只是新添加了一個xiaohai地址屬性,並沒有改變People類中的address類屬性), 可以通過呼叫類方法來修改相關類屬性) '''