Python類中的實例方法,類方法與靜態方法

從實現上看

class Simple:

    def __init__(self):

        pass

    def method(self):
        print('method!!!')
        pass
    
    @classmethod
    def classmethod(cls):
        print('classmethod!!!')
        pass
    
    @staticmethod
    def staticmethod():
        print('staticmethod!!!')
        pass

其中,實例方法傳入的第一個參數是self, 類方法傳入的第一個參數是類本身,靜態方法沒有參數的限制。
從調用方法上看

Simple.staticmethod()
staticmethod!!!
Simple.classmethod()
classmethod!!!
Simple.method()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: method() missing 1 required positional argument: 'self'

可以看出類方法與靜態方法都支持從類這個層次上進行調用,而實例方法不行

simple = Simple()
simple.method()
method!!!
simple.classmethod()
class method!!!
simple.staticmethod()
staticmethod!!!

從這裏可以看出,三種方法都支持實例化之後進行調用
實例化之後與實例化之前的差別

simple.method is Simple.method
False
simple.staticmethod is Simple.staticmethod
True
simple.classmethod is Simple.classmethod
False

可以看出,靜態方法在實例化之前與之後是不發生變化的。而實例方法與類方法就不同了,在實例化之前與之後都已經不是同一個對象了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章