python之静态和类方法:staticmethod和classmethod内置函数

假设要计算从一个类中产生了多少实例,类的属性是由所有实例共享的:

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)