Python中有趣在__call__函数

作者:junjie 时间:2022-04-04 14:06:22 

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)。


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) #We make a cow
dog = Animal('flopp', 4) #We can make many animals
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 #here __str__ metod work

#We give food to cow
cow('gras')
print cow.stomach

#We give food to dog
dog('bone')
dog('beef')
print dog.stomach

#What comes inn most come out
print cow.poop()
print cow.stomach #Empty stomach

'''-->output
We have 2 animales a cow name king and dog named flopp,both have 4 legs
A animal named king
['gras']
['bone', 'beef']
gras
[]
'''
标签:Python,call,函数
0
投稿

猜你喜欢

  • ASP技巧:Script块不能放在另一个Script 块内

    2009-08-19 17:17:00
  • 一个不错网速测试代码

    2008-07-20 13:41:00
  • 分享下页面关键字抓取www.icbase.com站点代码(带asp.net参数的)

    2023-11-17 02:40:14
  • 自定义用于ASP Web站点的 SQL 7.0 数据库

    2008-10-28 21:09:00
  • python提取页面内url列表的方法

    2022-12-26 15:29:27
  • Oracle In和exists not in和not exists的比较分析

    2009-08-27 10:07:00
  • Python求两点之间的直线距离(2种实现方法)

    2021-03-28 19:24:46
  • Python Vaex实现快速分析100G大数据量

    2021-05-24 08:48:58
  • python日期相关操作实例小结

    2021-07-14 18:39:13
  • 存贮查询与运行时查询孰优孰劣?

    2009-11-01 15:13:00
  • 利用PyQt5生成过年春联

    2023-05-23 21:14:22
  • python利用matplotlib库绘制饼图的方法示例

    2022-12-17 15:16:50
  • asp 读取文件和保存文件函数代码

    2011-04-04 11:17:00
  • 搜索结果页(SERP):个性化如何影响用户行为?

    2009-07-22 21:00:00
  • 详解Python如何制作自动发送微信的程序

    2021-06-04 13:24:53
  • Python实现随机划分图片数据集的示例代码

    2021-08-01 16:35:32
  • 如何做一个计数器并让人家申请使用?

    2010-07-11 21:13:00
  • python 列表输出重复值以及对应的角标方法

    2021-06-19 13:29:57
  • django redis的使用方法详解

    2023-08-03 10:54:30
  • python计算机视觉OpenCV库实现实时摄像头人脸检测示例

    2022-05-17 22:41:50
  • asp之家 网络编程 m.aspxhome.com