一般來說,要使用某個類的方法,需要先實例化一個對象再調(diào)用方法。而使用@staticmethod或@classmethod,就可以不需要實例化,直接通過類名就可以實現(xiàn)調(diào)用。
使用:直接類名.方法名()?來調(diào)用。
@staticmethod不需要表示自身對象的self和自身類的cls參數(shù)(這兩個參數(shù)都不需要添加),就跟使用函數(shù)一樣。
使用:直接類名.屬性名?或?直接類名.方法名。# 直接類名 也可以 直接類名( )
@classmethod也不需要self參數(shù),但第一個參數(shù)需要是表示自身類的cls參數(shù)。
使用:直接類名.屬性名 或?直接類名.方法名。
注:兩者定義的裝飾器調(diào)用方法一樣,如果在@staticmethod中要調(diào)用到這個類的一些屬性方法,只能直接類名.屬性名或類名.方法名。而@classmethod因為持有cls參數(shù),可以來調(diào)用類的屬性,類的方法,實例化對象等。
通常情況下,在類中定義的所有函數(shù)(注意了,這里說的就是所有,跟self啥的沒關(guān)系,self也只是一個再普通不過的參數(shù)而已)都是對象的綁定方法,對象在調(diào)用綁定方法時會自動將自己作為參數(shù)傳遞給方法的第一個參數(shù)。除此之外還有兩種常見的方法:靜態(tài)方法和類方法,二者是為類量身定制的,但是實例非要使用,也不會報錯。
是一種普通函數(shù),位于類定義的命名空間中,不會對任何實例類型進(jìn)行操作,python為我們內(nèi)置了函數(shù)staticmethod來把類中的函數(shù)定義成靜態(tài)方法:
class Foo: def spam(x,y,z): #類中的一個函數(shù),千萬不要懵逼,self和x啥的沒有不同都是參數(shù)名 print(x,y,z) spam=staticmethod(spam) #把spam函數(shù)做成靜態(tài)方法
基于之前所學(xué)裝飾器的知識,@staticmethod 等同于spam=staticmethod(spam),于是:
class Foo: @staticmethod #裝飾器 def spam(x,y,z): print(x,y,z)
使用演示:
print(type(Foo.spam)) #類型本質(zhì)就是函數(shù)Foo.spam(1,2,3) #調(diào)用函數(shù)應(yīng)該有幾個參數(shù)就傳幾個參數(shù)f1=Foo()f1.spam(3,3,3) #實例也可以使用,但通常靜態(tài)方法都是給類用的,實例在使用時喪失了自動傳值的機(jī)制'''<class 'function'>2 33 3'''
應(yīng)用場景:編寫類時需要采用很多不同的方式來創(chuàng)建實例,而我們只有一個__init__函數(shù),此時靜態(tài)方法就派上用場了。
class Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day @staticmethod def now(): #用Date.now()的形式去產(chǎn)生實例,該實例用的是當(dāng)前時間 t=time.localtime() #獲取結(jié)構(gòu)化的時間格式 return Date(t.tm_year,t.tm_mon,t.tm_mday) #新建實例并且返回 @staticmethod def tomorrow():#用Date.tomorrow()的形式去產(chǎn)生實例,該實例用的是明天的時間 t=time.localtime(time.time() 86400) return Date(t.tm_year,t.tm_mon,t.tm_mday)a=Date('1987',11,27) #自己定義時間b=Date.now() #采用當(dāng)前時間c=Date.tomorrow() #采用明天的時間print(a.year,a.month,a.day)print(b.year,b.month,b.day)print(c.year,c.month,c.day)
?類方法是給類用的,類在使用時會將類本身當(dāng)做參數(shù)傳給類方法的第一個參數(shù),python為我們內(nèi)置了函數(shù)classmethod來把類中的函數(shù)定義成類方法:
class A: x=1 @classmethod def test(cls): print(cls,cls.x)class B(A): x=2B.test()'''輸出結(jié)果:<class '__main__.B'> 2'''
應(yīng)用場景:
import timeclass Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day @staticmethod def now(): t=time.localtime() return Date(t.tm_year,t.tm_mon,t.tm_mday)class EuroDate(Date): def __str__(self): return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)e=EuroDate.now()print(e) #我們的意圖是想觸發(fā)EuroDate.__str__,但是結(jié)果為'''輸出結(jié)果:<__main__.Date object at 0x1013f9d68>'''
因為e就是用Date類產(chǎn)生的,所以根本不會觸發(fā)EuroDate.__str__,解決方法就是用classmethod。
import timeclass Date: def __init__(self,year,month,day): self.year=year self.month=month self.day=day # @staticmethod # def now(): # t=time.localtime() # return Date(t.tm_year,t.tm_mon,t.tm_mday) @classmethod #改成類方法 def now(cls): t=time.localtime() return cls(t.tm_year,t.tm_mon,t.tm_mday) #哪個類來調(diào)用,即用哪個類cls來實例化class EuroDate(Date): def __str__(self): return 'year:%s month:%s day:%s' %(self.year,self.month,self.day)e=EuroDate.now()print(e) #我們的意圖是想觸發(fā)EuroDate.__str__,此時e就是由EuroDate產(chǎn)生的,所以會如我們所愿'''輸出結(jié)果:year:2017 month:3 day:3'''
強(qiáng)調(diào),注意注意注意:靜態(tài)方法和類方法雖然是給類準(zhǔn)備的,但是如果實例去用,也是可以用的,只不過實例去調(diào)用的時候容易讓人混淆,不知道你要干啥。
x=e.now() #通過實例e去調(diào)用類方法也一樣可以使用,靜態(tài)方法也一樣print(x)'''輸出結(jié)果:year:2017 month:3 day:3'''
#__str__定義在類內(nèi)部,必須返回一個字符串類型,#什么時候會出發(fā)它的執(zhí)行呢?打印由這個類產(chǎn)生的對象時,會觸發(fā)執(zhí)行class People: def __init__(self,name,age): self.name=name self.age=age def __str__(self): return '<name:%s,age:%s>' %(self.name,self.age)p1=People('egon',18)print(p1)str(p1) #----->p1.__str__()