__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
-