類方法和靜態(tài)方法
- @staticmethod 表示下面 方法是靜態(tài)方法
- @classmethod 表示下面的方法是類方法
例子
>>> class StaticMethod(object):
... @staticmethod
... def foo():
... print "this is static method foo()"
...
>>> class ClassMethod:
... @classmethod
... def bar(cls):
... print "this is class method bar()"
... print "bar() is part of class:",cls.__name__
...
>>> static_foo = StaticMethod()
>>> static_foo.foo()
this is static method foo()
>>> StaticMethod.foo()
this is static method foo()
>>>
>>> class_bar = ClassMethod()
>>> class_bar.bar()
this is class method bar()
bar() is part of class: ClassMethod
>>> ClassMethod.bar()
this is class method bar()
從以上例子寸痢,可以看出:
- 無論是類方法南蓬、靜態(tài)方法,方法后面的括號內(nèi)呐舔;
- 都可以不用加self作為第一個參數(shù),都可以使用實例調(diào)用方法或者類名調(diào)用方法。
- 在類方法的參數(shù)中滥崩,需要使用cls作為參數(shù)。
- 在靜態(tài)方法的參數(shù)中讹语,沒有self參數(shù)钙皮,就無法訪問實例變量,類和實例的屬性了顽决。
類方法和靜態(tài)方法的區(qū)別
>>> class Kls(object):
... def __init__(self,data):
... self.data = data
... def printd(self):
... print(self.data)
... @staticmethod
... def smethod(*arg):
... print 'Static:',arg
... @classmethod
... def cmethod(*arg):
... print 'Class:',arg
...
>>> ik = Kls(24)
>>> ik.printd()
24
>>> ik.smethod()
'Static:', ()
>>> ik.cmethod()
'Class:', (<class '__main__.Kls'>,)
>>> Kls.printd()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method printd() must be called with Kls instance as first argument (got nothing instead)
>>> Kls.smethod()
'Static:', ()
>>> Kls.cmethod()
'Class:', (<class '__main__.Kls'>,)
從以上例子可以看出短条,類方法默認的第一個參數(shù)是他所屬的類的對象,而靜態(tài)方法沒有才菠。