python 實例方法、靜態方法、類方法的區別


一、函數與方法

  在類的定義中,通過類調用和實例調用是不一樣的,一個是 function 類型,另一個是 method 類型。他們的主要區別在於,函數的 傳參都是顯式傳遞的 而方法中 傳參往往都會有隱式傳遞的,具體根據於調用方。例如示例中的 test().say通過實例調用的方式會隱式傳遞 self數據。

class test:
    def say(self):
        pass

print(test.say)     # <function test.say at 0x000001F5FD475730>
print(test().say)   # <bound method test.say of <__main__.test object at 0x000001F5FD452940>>

 

二、python 類的實例方法

  通常情況下,在類中定義的普通方法即為類的實例方法,實例方法第一個參數是 self(self 是一種約定習慣) 代表實例本身,當調用某個實例方法時,該實例的對象引用作為第一個參數 self 隱式的傳遞到方法中。

  簡單來說實例方法是需要在類實例化后才能調用,如下:

class test:
    math = 100
    # 類構造方法也是實例方法
    def __init__(self):
        self.Chinese = 90
        self.English = 80
    # 實例方法
    def say(self):
        print('我的語文成績是:{}'.format(self.Chinese))

# 實例化
A = test()
# 調用實例方法
A.say()
print(A.say)  # <bound method test.say of <__main__.test object at 0x0000020C07F28978>>

 若想直接調用方法,需要手動為 self 傳入實例,如下:

# 實例化
A = test()
# 為self傳入實例 
test.say(A)

 

三、python 類的靜態方法

  類的靜態方法和我們自定義的函數基本沒什么區別,沒有 self,且不能訪問類屬性,實際項目中很少用到,因為可以使用普通函數替代。

  靜態方法需要使用 @staticmethod 裝飾器聲明。

  有兩種調用方式:類.方法名 和 實例化調用 。

class test:
    math = 100
    # 類構造方法也是實例方法
    def __init__(self):
        self.Chinese = 90
        self.English = 80
    @staticmethod
    def say():
        print('我的語文成績是:90')

# 類.方法名
test.say()
print(test.say)  # <function test.say at 0x000001C2620257B8>
# 實例化
A=test()
A.say()
print(A.say)     # <function test.say at 0x000001C2620257B8>

 

四、python 類的類方法

  類的類方法也必須包含一個參數,通常約定為 cls ,cls 代表 類本身(注意不是實例本身,是有區別的),python 會自動將類本身傳給 cls,所有這個參數也不需要我們傳值。

  類方法必須需要使用 @classmethod 裝飾器申明。

  兩種方式調用:類.方法名 和 實例調用。

class test:
    math = 100
    # 類構造方法也是實例方法
    def __init__(self):
        self.Chinese = 90
        self.English = 80
    @classmethod
    def say(cls):
        print('我的數學成績是:{}'.format(cls.math))

# 類.方法名
test.say()
print(test.say)      # <bound method test.say of <class '__main__.test'>>
# 實例化調用
test().say()
print(test().say)    # <bound method test.say of <class '__main__.test'>>

 

總結一下:

實例方法:可以獲取類屬性、構造函數定義的變量,屬於 method 類型。只能通過實例化調用。

靜態方法:不能獲取類屬性、構造函數定義的變量,屬於 function 類型。兩種調用方式:類.方法名 ,實例化調用。

類方法 :可以獲取類屬性,不能獲取構造函數定義的變量,屬於 method 類型。兩種調用方式:類.方法名 ,實例化調用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM