Python:staticmethod 和 classmethod的比較

class A(object):
    def foo(self, x):
        print "executing foo(%s, %s)" % (self, x)

    @classmethod
    def class_foo(cls, x):
        print "executing class_foo(%s, %s)" % (cls, x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" % x    

a = A()

看一下輸出:
常規定義的方法:函數

a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)

classmethod的輸出:code

a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

以上代碼能夠看出,建立classmethod時,該對象實例的class cls 是做爲第一個輸入變量的,而不是該實例自己(若是是實例自己的話,第一個輸入變量就是self, 就是一個普通的咱們經常使用的狀況了)對象

這樣建立的classmethod 有什麼好處呢? 好處就是你能夠直接用class來call這個函數,而不須要費周折地先去建立一個實例(class instance)。 ip

而staticmethods呢,它沒有默認的第一個輸入變量。 它跟咱們在一個空白的script裏寫的一個普通的函數 def fund():... 沒有任何實質的區別。惟一的不一樣就是你要經過 類class 或者實例instance 來call它。 ci

With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class.get

本文參考來源:https://stackoverflow.com/que...it

相關文章
相關標籤/搜索