天天看點

Python靜态方法(staticmethod)、類方法(classmethod)、__str__的用法

一、使用與特性

1.1、使用說明:

一般來說,要使用某個類的方法,需要先執行個體化一個對象再調用方法。而使用@staticmethod或@classmethod,就可以不需要執行個體化,直接通過類名就可以實作調用。

使用:直接類名.方法名() 來調用。

1.2、差別:

@staticmethod不需要表示自身對象的self和自身類的cls參數(這兩個參數都不需要添加),就跟使用函數一樣。

使用:直接類名.屬性名 或 直接類名.方法名。# 直接類名 也可以 直接類名( )

@classmethod也不需要self參數,但第一個參數需要是表示自身類的cls參數。

使用:直接類名.屬性名 或 直接類名.方法名。

注:兩者定義的裝飾器調用方法一樣,如果在@staticmethod中要調用到這個類的一些屬性方法,隻能直接類名.屬性名或類名.方法名。而@classmethod因為持有cls參數,可以來調用類的屬性,類的方法,執行個體化對象等。

二、靜态方法(staticmethod)                                                            

通常情況下,在類中定義的所有函數(注意了,這裡說的就是所有,跟self啥的沒關系,self也隻是一個再普通不過的參數而已)都是對象的綁定方法,對象在調用綁定方法時會自動将自己作為參數傳遞給方法的第一個參數。除此之外還有兩種常見的方法:靜态方法和類方法,二者是為類量身定制的,但是執行個體非要使用,也不會報錯。

是一種普通函數,位于類定義的命名空間中,不會對任何執行個體類型進行操作,python為我們内置了函數staticmethod來把類中的函數定義成靜态方法:

class Foo:
    def spam(x,y,z): #類中的一個函數,千萬不要懵逼,self和x啥的沒有不同都是參數名
        print(x,y,z)
    spam=staticmethod(spam) #把spam函數做成靜态方法
           

基于之前所學裝飾器的知識,@staticmethod 等同于spam=staticmethod(spam),于是:

class Foo:
    @staticmethod #裝飾器
    def spam(x,y,z):
        print(x,y,z)
           

使用示範:

print(type(Foo.spam)) #類型本質就是函數
Foo.spam(1,2,3) #調用函數應該有幾個參數就傳幾個參數

f1=Foo()
f1.spam(3,3,3) #執行個體也可以使用,但通常靜态方法都是給類用的,執行個體在使用時喪失了自動傳值的機制

'''
<class 'function'>
2 3
3 3
'''
           

應用場景:編寫類時需要采用很多不同的方式來建立執行個體,而我們隻有一個__init__函數,此時靜态方法就派上用場了。

class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
    @staticmethod
    def now(): #用Date.now()的形式去産生執行個體,該執行個體用的是目前時間
        t=time.localtime() #擷取結構化的時間格式
        return Date(t.tm_year,t.tm_mon,t.tm_mday) #建立執行個體并且傳回
    @staticmethod
    def tomorrow():#用Date.tomorrow()的形式去産生執行個體,該執行個體用的是明天的時間
        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() #采用目前時間
c=Date.tomorrow() #采用明天的時間

print(a.year,a.month,a.day)
print(b.year,b.month,b.day)
print(c.year,c.month,c.day)
           

三、類方法(classmethod)                                                                

 類方法是給類用的,類在使用時會将類本身當做參數傳給類方法的第一個參數,python為我們内置了函數classmethod來把類中的函數定義成類方法:

class A:
    x=1
    @classmethod
    def test(cls):
        print(cls,cls.x)

class B(A):
    x=2
B.test()

'''
輸出結果:
<class '__main__.B'> 2
'''
           

應用場景:

import time
class 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) #我們的意圖是想觸發EuroDate.__str__,但是結果為
'''
輸出結果:
<__main__.Date object at 0x1013f9d68>
'''
           

因為e就是用Date類産生的,是以根本不會觸發EuroDate.__str__,解決方法就是用classmethod。

import time
class 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) #哪個類來調用,即用哪個類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) #我們的意圖是想觸發EuroDate.__str__,此時e就是由EuroDate産生的,是以會如我們所願
'''
輸出結果:
year:2017 month:3 day:3
'''
           

強調,注意注意注意:靜态方法和類方法雖然是給類準備的,但是如果執行個體去用,也是可以用的,隻不過執行個體去調用的時候容易讓人混淆,不知道你要幹啥。

x=e.now() #通過執行個體e去調用類方法也一樣可以使用,靜态方法也一樣
print(x)
'''
輸出結果:
year:2017 month:3 day:3
'''
           

四、附加知識點__str__的用法      

# __str__定義在類内部,必須傳回一個字元串類型,
# 什麼時候會觸發它的執行呢?列印由這個類産生的對象時,會觸發執行

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__()