python中實例方法,類方法,靜態方法簡單理解


按照字面名稱來理解的話:

實例方法就是實例化對象的方法,綁定在實例對象上

類方法就是類自己的方法,不需要實例化對象,類自己就是對象,直接綁定在類上

靜態方法就是普通的函數,函數作為對象,不過是封裝在類的內部,通過類.方法引用

從參數上看:

實例方法默認參數是self

類方法默認參數是cls

靜態方法可以沒有

舉個例子:

class Test():
    
    def a(self):
        print(self.a)

    @classmethod
    def b(cls):
        print(cls.b)

    @staticmethod
    def c():
        print(Test.c)

實例化一個對象

tmp = Test()
tmp.a()
tmp.b()
tmp.c()

輸出:
<bound method Test.a of <__main__.Test object at 0x02145110>>
<bound method Test.b of <class '__main__.Test'>>
<function Test.c at 0x021424F8>

直接通過類去調用(以類本身為對象)

Test.a()
Test.b()
Test.c()

輸出:
TypeError: a() missing 1 required positional argument: 'self'
<bound method Test.b of <class '__main__.Test'>>
<function Test.c at 0x021D24F8>

類自己實例化

print(Test())
print(Test)
Test().a()
Test().b()
Test().c()

輸出
<__main__.Test object at 0x006E50B0>
<class '__main__.Test'>
<bound method Test.a of <__main__.Test object at 0x006E5790>>
<bound method Test.b of <class '__main__.Test'>>
<function Test.c at 0x006E24F8>

這里Test()與Test().a()在內存中對象不同,是因為一個是類對象,一個是實例方法對象

 

簡單來說,@classmethod就是不用實例化,直接用類內部的方法;@staticmethod則是為封裝類好看,為了滿足強迫症,把方法裝進類里面,實際大家都可以用

 


免責聲明!

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



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