self-confidence,the source of all the power

导航

python __call__ 函数

 

 __call__

Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。

换句话说,我们可以把这个类型的对象当作函数来使用,相当于 重载了括号运算符。

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)

 

    1. class Animal(object):
    2. def __init__(self, name, legs):
    3. self.name = name
    4. self.legs = legs
    5. self.stomach = []
    6.  
    7. def __call__(self,food):
    8. self.stomach.append(food)
    9.  
    10. def poop(self):
    11. if len(self.stomach) > 0:
    12. return self.stomach.pop(0)
    13.  
    14. def __str__(self):
    15. return 'A animal named %s' % (self.name)
    16.  
    17. cow = Animal('king', 4) #We make a cow
    18. dog = Animal('flopp', 4) #We can make many animals
    19. print 'We have 2 animales a cow name %s and dog named %s,both have %s legs' % (cow.name, dog.name, cow.legs)
    20. print cow #here __str__ metod work
    21.  
    22. #We give food to cow
    23. cow('gras')
    24. print cow.stomach
    25.  
    26. #We give food to dog
    27. dog('bone')
    28. dog('beef')
    29. print dog.stomach
    30.  
    31. #What comes inn most come out
    32. print cow.poop()
    33. print cow.stomach #Empty stomach
    34.  
    35. '''-->output
    36. We have 2 animales a cow name king and dog named flopp,both have 4 legs
    37. A animal named king
    38. ['gras']
    39. ['bone', 'beef']
    40. gras
    41. []
    42. '''

posted on 2011-04-29 15:56  漩涡鸣人  阅读(29865)  评论(0编辑  收藏  举报