python之静态和类方法:staticmethod和classmethod内置函数
2012-05-09 15:51
986 查看
假设要计算从一个类中产生了多少实例,类的属性是由所有实例共享的:
这里的问题是无绑定函数并不完全等同于简单函数。直接调用Sapm.printNumInstances是错误的,但可以调用实例的printNumInatances,如:
现在可以编写和类相关的简单函数。
注意 :程序最后两行是重新赋值方法名smeth和cmeth而已。
下面是和开头等效的静态方法:
class Sapm: numInstances = 0 def __init__(self): Spam.numInstances = Spam.numInstances + 1 def printNumInstances(): print "Number of instances created: ", Spam.numInstances这样行不通:printNumInstance方法在调用时,还是需要传入一个实例,因为这个函数适合类相结合的(即使def首行中没有self)。
这里的问题是无绑定函数并不完全等同于简单函数。直接调用Sapm.printNumInstances是错误的,但可以调用实例的printNumInatances,如:
a=Sapm() a.printNumInstances()
现在可以编写和类相关的简单函数。
class Multi: def imeth(self,x): #normal instance method print self,x def smeth(x): #static:no intance passed print x def cmeth(cls,x): #class: gets class,not instance print cls,x smeth = staticmethod(smeth) #make smeth a static method cmeth = classmethod(cmeth) #make cmeth a class method
注意 :程序最后两行是重新赋值方法名smeth和cmeth而已。
>>> obj = Multi() >>> obj.imeth(1) <__main__.Multi instance at 0x00B9EC60> 1 >>> Multi.imeth(obj, 2) #normal call <__main__.Multi instance at 0x00B9EC60> 2 >>> Multi.smeth(3) #static call 3 >>> obj.smeth(4) 4 >>> Multi.cmeth(5) #class call: through class __main__.Multi 5 >>> obj.cmeth(6) #class call: through instance __main__.Multi 6
下面是和开头等效的静态方法:
class Sapm: numInstances = 0 def __init__(self): Spam.numInstances = Spam.numInstances + 1 def printNumInstances(): print "Number of instances created: ", Spam.numInstances
printNumInstances = staticmethod(printNumInstances)
相关文章推荐
- python-静态方法staticmethod、类方法classmethod、属性方法property
- python-静态方法staticmethod、类方法classmethod、属性方法property
- python 静态方法staticmethod和类方法classmethod
- python的classmethod和staticmethod方法
- python基础----特性(property)、静态方法(staticmethod)、类方法(classmethod)、__str__的用法
- Python中普通方法、staticmethod、classmethod的区别
- python 类中staticmethod,classmethod,普通方法
- Python内置函数的staticmethod()与classmethod(),@staticmethod,@classmethod
- python 中 @classmethod 、staticmethod 和 普通方法 的区别
- python中 classmethod、staticmethod和普通方法的区别
- 类方法 @classmethod 静态方法@staticmethod
- python 3全栈开发-面向对象之绑定方法(classmethod与staticmethod的区别)、多态、封装的特性property
- python中7种实现单例模式的方法:staticmethod、classmethod、类属性方法、__new__、装饰器、元类、名字覆盖
- 静态方法(staticmethod),类方法(classmethod)与实例方法
- python staticmethod,classmethod方法的使用和区别以及property装饰器的作用
- python的静态方法以及@staticmethod或@classmethod的区别
- Python中staticmethod方法和classmethod方法区别
- Python标准库:内置函数hasattr() getattr() setattr() 函数使用方法详解
- python一种用classmethod实现单例模式方法的探讨
- python普通方法、类方法、静态方法