1、類的方法,按照調用方式可以分為3種,實例方法、靜態方法、和類方法
1.1 實例方法
實例方法只能通過實例對象調用,不能通過類進行調用。實例方法再定義時候使用關鍵字self,self代表實例對象本身。
class A(): x=100 def fun(self,y): self.x+=y a=A() a.fun(10) print(a.x) A.fun(10) *****結果****** 110 Traceback (most recent call last): #類調用錯誤 File "/home/34f17b632da0cc986bc0f291c0518783.py", line 8, in <module> A.fun(10) TypeError: fun() missing 1 required positional argument: 'y'
1.2 靜態方法
靜態方法可以使用實例對象調用,也可以使用類進行調用,他的的特點沒有參數限制,定義時需要在函數前加@staticmethod
class B(): @staticmethod def fun(): print('hello,word') a=B() a.fun() #實例調用 B.fun() #類調用 ***結果***** hello,word hello,word
1.3 類方法:
可以被類調用,也可以被實例對象調用,實例調用可以給類增加屬性,類的屬性修改需要通過類進行修改,類方法需要使用關鍵字cls,定義時候需要在函數前加@classmethod
class Student(object): school='szu' @classmethod def printmassage(cls): print(cls.school) s1=Student() Student.printmassage() s1.printmassage() s1.school='beijingizhong' #為類的實例增加屬性,類的實例school本身不改變 print(Student.school)#szu print(s1.school)#beijingizhong Student.school='shanghaiyizhong'#通過類對類的屬性school做修改,類的屬性發生改變 s1.printmassage() #shanghaiyizhong *****結果******* szu szu szu beijingizhong shanghaiyizhong
2、靜態屬性
靜態屬性。@property。作用就是把類的函數屬性,封裝成類似數據屬性。再調用函數printmassage 時候,必須不帶()執行。
class Student(object): school='szu' @property def printmassage(self): print('aaaa') s1=Student() s1.printmassage #aaaa