[Python進階] Python定義類方法

Python中的幾種定義類方法:常規方式,@property修飾方式,@classmethod修飾方式,@staticmethod修飾方式。python

class Test(object):
    def __init__(self):
        self.name = 'eappo'

    def fun(self, x):
        print('self:', self, x)

    @property
    def property_fun(self):
        print('@property', self, self.name)

    @classmethod
    def class_fun(cls, x):
        print('@classmethod cls:', cls, x)

    @staticmethod
    def static_fun(x):
        print('@staticmethod', x)

if __name__ == '__main__':
    a = Test()
    a.fun('fun')
    a.property_fun
    a.class_fun('class_fun')
    a.static_fun('static_fun')

運行結果: 編程

self: <__main__.Test object at 0x0000023DC8BAD208> fun
@property <__main__.Test object at 0x0000023DC8BAD208> eappo
@classmethod cls: <class '__main__.Test'> class_fun
@staticmethod static_fun

self和cls的區別不是強制的,只是PEP8中一種編程風格,self一般用做實例方法的第一參數,cls一般用做類方法的第一參數。即一般用self來傳遞當前類對象的實例,cls傳遞當前類對象。app

常規的類方法

定義時都須要經過self參數隱式的傳遞當前對象的實例函數

調用時能夠隱式或者顯式ui

if __name__ == '__main__':
    a = Test()
    a.fun(1)
    Test.fun(a, 1)

屬性函數(@property):

  • 將類方法轉換爲只讀屬性
  • 從新實現一個屬性的setter和getter方法
class TestProperty(object):
    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, v):
        self._score = v

if __name__ == '__main__':

    s = TestProperty()
    s.score = 10
    print(s.score)

運行結果:spa

10

類方法(@classmethod)

@classmethod修飾的方法須要經過cls參數傳遞當前類對象code

常規方法調用類的方法時必須實例化對象,可是類方法能夠直接經過類來調用方法。對象

if __name__ == '__main__':
    Test.class_fun(1)
    Test.fun(1)

運行結果:繼承

@classmethod cls: <class '__main__.Test'> 1
Traceback (most recent call last):
  File "F:/PythonSpace/ClassMethod/Test.py", line 31, in <module>
    Test.fun(1)
TypeError: fun() missing 1 required positional argument: 'x'

靜態方法(@staticmethod)

@staticmethod修飾的方法定義與普通函數是同樣的。只不過該方法位於類定義的命名空間中,不會對任何實例類型進行操做,類能夠不用實例化也能夠實例化後調用 。get

特別強調的是,繼承與覆蓋普通類函數是同樣的。

相關文章
相關標籤/搜索