__call__python
Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。app
换句话说,咱们能够把这个类型的对象看成函数来使用,至关于 重载了括号运算符。函数
- class g_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)。oop
- class Animal(object):
- def __init__(self, name, legs):
- self.name = name
- self.legs = legs
- self.stomach = []
-
- def __call__(self,food):
- self.stomach.append(food)
-
- def poop(self):
- if len(self.stomach) > 0:
- return self.stomach.pop(0)
-
- def __str__(self):
- return 'A animal named %s' % (self.name)
-
- cow = Animal('king', 4)
- dog = Animal('flopp', 4)
- print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
- print cow
-
- cow('gras')
- print cow.stomach
-
- dog('bone')
- dog('beef')
- print dog.stomach
-
- print cow.poop()
- print cow.stomach
-