zoukankan      html  css  js  c++  java
  • 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. '''  
  • 相关阅读:
    RPC
    动词 or 名词 :这是一个问题 【转载】
    js 如何清除setinterval
    封装动画特效
    飞入特效
    建字段_添加数据_生成json.php
    mybatis由浅入深day02_9.3.5使用生成的代码_9.4逆向工程注意事项
    mybatis由浅入深day02_9逆向工程
    mybatis由浅入深day02_8spring和mybatis整合
    mybatis由浅入深day02_7.4mybatis整合ehcache_7.5二级缓存应用场景_7.6二级缓存局限性
  • 原文地址:https://www.cnblogs.com/paranoia/p/6196873.html
Copyright © 2011-2022 走看看