首頁  >  文章  >  後端開發  >  裝飾器@staticmethod和@classmethod有什麼差別

裝飾器@staticmethod和@classmethod有什麼差別

anonymity
anonymity原創
2019-05-24 14:58:206423瀏覽

裝飾器@staticmethod和@classmethod的差異是:@staticmethod不需要self和cls參數,@classmethod不需要self參數,但需要cls參數。

裝飾器@staticmethod和@classmethod有什麼差別

通常來說,我們使用一個類別的方法時,首先要實例化這個類,再用實例化的類別來呼叫其方法

class Test(object):
    """docstring for Test"""
    def __init__(self, arg=None):
        super(Test, self).__init__()
        self.arg = arg
    def say_hi(self):
        print 'hello wrold'
def main():
    test = Test() //1. 首先实例化test类
    test.say_hi() //2. 再调用类的方法
if __name__ == '__main__':
    main()

而使用@staticmethod或@classmethod,就可以不需要實例化,直接類別名稱.方法名稱()來呼叫。

這有利於組織程式碼,把某些應該屬於某個類別的函數給放到那個類別裡去,同時有利於命名空間的整潔。

class Test(object):
    """docstring for Test"""
    def __init__(self, arg=None):
        super(Test, self).__init__()
        self.arg = arg
    def say_hi(self):
        print 'hello wrold'
    @staticmethod
    def say_bad():
        print 'say bad'
    @classmethod
    def say_good(cls):
        print 'say good'
def main():
    test = Test()
    test.say_hi()
    Test.say_bad() //直接类名.方法名()来调用
    Test.say_good() //直接类名.方法名()来调用
if __name__ == '__main__':
    main()

@staticmethod或@classmethod的區別

類別的普通方法,地一個參數需要self參數來表示自己。

@staticmethod不需要表示自身物件的self和自身類別的cls參數,就跟使用函數一樣。

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

以上是裝飾器@staticmethod和@classmethod有什麼差別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn