python __call__ 函数

 __call__

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

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

[python]  view plain  copy
  1. class g_dpm(object):  
  2.   
  3.     def __init__(self, g):  
  4.         self.g = g  
  5.   
  6.     def __call__(self, t):  
  7.         return (self.g*t**2)/2  

计算地球场景的时候,我们就可以令e_dpm = g_dpm(9.8)s = e_dpm(t)

[python]  view plain  copy
  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.    

[python]  view plain  copy
  1. '''''-->output 
  2. We have 2 animales a cow name king and dog named flopp,both have 4 legs 
  3. A animal named king 
  4. ['gras'] 
  5. ['bone', 'beef'] 
  6. gras 
  7. [] 
  8. '''  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值