Python中有趣在__call__函数

yipeiwu_com6年前Python基础

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
[]
'''

相关文章

Cython编译python为so 代码加密示例

1. 编译出来的so比网上流传的其他方法小很多。 2. language_level  是python的主版本号,如果python版本是2.x,目前的版本Cython需要人工指...

python调用百度语音识别api

python调用百度语音识别api

最近在处理语音检索相关的事。 其中用到语音识别,调用的是讯飞与百度的api,前者使用js是实现,后者用python3实现(因为自己使用python) 环境: python3.5 ce...

python 将字符串完成特定的向右移动方法

# 将字符串中的元素完成特定的向右移动,参数:字符串、移动长度 如:abcdef,移动2,结果:efabcd #原始方法,基本思想:末尾元素移动到开头,其他的元素依次向后移动.代码如下:...

bpython 功能强大的Python shell

bpython 功能强大的Python shell

Python是一个非常实用、流行的解释型编程语言,其优势之一就是可以借助其交互的shell进行探索式地编程。你可以试着输入一些代码,然后马上获得解释器的反馈,而不必专门写一个脚本。但是P...

浅析Windows 嵌入python解释器的过程

这次主要记录在windows下嵌入 python 解释器的过程,程序没有多少,主要是头文件与库文件的提取。 程序平台:windows10 64 bit、 Qt 5.5.1  M...