`

python 静态方法与类方法

阅读更多

staticmethod, classmethod 分别被称为静态方法和类方法。 

staticmethod
基本上和一个全局函数差不多,只不过可以通过类或类的实例对象(python里说光说对象总是容易产生混淆,
因为什么都是对象,包括类,而实际上类实例对象才是对应静态语言中所谓对象的东西)来调用而已,
不会隐式地传入任何参数。这个和静态语言中的静态方法比较像。

classmethod
是和一个class相关的方法,可以通过类或类实例调用,并将该class对象(不是class的实例对象)隐式地
当作第一个参数传入。就这种方法可能会比较奇怪一点,不过只要你搞清楚了python里class也是个真实地
存在于内存中的对象,而不是静态语言中只存在于编译期间的类型,就好办了。

正常的方法就是和一个类的实例对象相关的方法,通过类实例对象进行调用,并将该实例对象隐式地作为第一个参数传入,这个也和其它语言比较像。


区别:类方法需要额外的类变量cls,当有之类继承时,调用类方法传入的类变量cls是子类,而不是父类。类方法和静态方法都可以通过类对象和类的 实例对象访问。



①静态方法

>>> class Foo:
str = "I'm a static method."
def bar():
     print Foo.str
bar = staticmethod(bar)
>>> Foo.bar()
I'm a static method.


②类方法

>>> class Foo:
str = "I'm a static method."
def bar(cls):
     print cls.str
bar = classmethod(bar)
>>> Foo.bar()
I'm a static method.

 

上面的代码我们还可以写的更简便些(python2.4+新语法):

①静态方法

>>> class Foo:
str = "I'm a static method."
@staticmethod
def bar():
      print Foo.str
>>> Foo.bar()
I'm a static method.


②类方法

>>> class Foo:
str = "I'm a static method."
@classmethod
def bar(cls):
      print cls.str
>>> Foo.bar()
I'm a static method.
 

 


转自:http://hi.baidu.com/wutaof509/blog/item/b6687f299f6e6123d42af1bf.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics