Python的类方法和静态方法

2016-05-18  本文已影响36人  上发条的树

类方法和静态方法

  • @staticmethod 表示下面 方法是静态方法
  • @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()

从以上例子,可以看出:

类方法和静态方法的区别

>>> 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'>,)

从以上例子可以看出,类方法默认的第一个参数是他所属的类的对象,而静态方法没有。

上一篇 下一篇

猜你喜欢

热点阅读