首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

今天python

2012-08-31 
今日python【http://www.morningprincess.com/python_staticmethod_and_classmethod/】Python中staticmethod

今日python
【http://www.morningprincess.com/python_staticmethod_and_classmethod/】
Python中staticmethod和classmethod的区别

?

定义方式,传入的参数,调用方式都不相同。

staticmethod 不需要传入self和cls对象,只有一般的参数。可以通过实例或类对象进行调用。

classmethod需要传入cls对象,可以通过实例和类对象进行高用。

一般的method需要传入self实例对象。
staticmethod,classmethod相关于全局方法,一般用在抽象类或父类中。一般与具体的类无关。

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

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

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

?

'''
Created on 2012-3-23

@author: leonzhan
'''

class Foo1:
??? str = "I'm a static method, Foo1."
???
??? @staticmethod
??? def bar():
??????? print Foo1.str
Foo1.bar()


class Foo11(Foo1):
??? str = "I'm a static method, Foo11."
??? @staticmethod
??? def bar():
??????? print Foo11.str
Foo11.bar()


class Foo2:
??? str = "I'm a class method."
??? @classmethod
??? def bar(cls):
??????? print cls.str
Foo2.bar()

class Foo21(Foo2):
??? str="I'm class method Foo21"
??? @classmethod
??? def bar(cls):
??????? print cls.str

Foo21.bar()

if __name__ == '__main__':
??? pass

?

?

?

?

Python Decorator:

???????? http://yzjklove.iteye.com/blog/544427

?

?

热点排行