美文网首页
Python的类方法和静态方法

Python的类方法和静态方法

作者: 上发条的树 | 来源:发表于2016-05-18 17:12 被阅读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()

从以上例子,可以看出:

  • 无论是类方法、静态方法,方法后面的括号内;
  • 都可以不用加self作为第一个参数,都可以使用实例调用方法或者类名调用方法。
  • 在类方法的参数中,需要使用cls作为参数。
  • 在静态方法的参数中,没有self参数,就无法访问实例变量,类和实例的属性了。

类方法和静态方法的区别

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

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

相关文章

网友评论

      本文标题:Python的类方法和静态方法

      本文链接:https://www.haomeiwen.com/subject/clswrttx.html