Python中有趣在__call__函数
Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。
换句话说,我们可以把这个类型的对象当作函数来使用,相当于重载了括号运算符。
classg_dpm(object): def__init__(self,g): self.g=g def__call__(self,t): return(self.g*t**2)/2
计算地球场景的时候,我们就可以令e_dpm=g_dpm(9.8),s=e_dpm(t)。
classAnimal(object):
def__init__(self,name,legs):
self.name=name
self.legs=legs
self.stomach=[]
def__call__(self,food):
self.stomach.append(food)
defpoop(self):
iflen(self.stomach)>0:
returnself.stomach.pop(0)
def__str__(self):
return'Aanimalnamed%s'%(self.name)
cow=Animal('king',4)#Wemakeacow
dog=Animal('flopp',4)#Wecanmakemanyanimals
print'Wehave2animalesacowname%sanddognamed%s,bothhave%slegs'%(cow.name,dog.name,cow.legs)
printcow#here__str__metodwork
#Wegivefoodtocow
cow('gras')
printcow.stomach
#Wegivefoodtodog
dog('bone')
dog('beef')
printdog.stomach
#Whatcomesinnmostcomeout
printcow.poop()
printcow.stomach#Emptystomach
'''-->output
Wehave2animalesacownamekinganddognamedflopp,bothhave4legs
Aanimalnamedking
['gras']
['bone','beef']
gras
[]
'''