Python中有趣在__call__函数

yipeiwu_com5年前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
[]
'''

相关文章

学Python 3的理由和必要性

Python很多年前就已经出现了,并且还在不断发展。本书第1版基 于Python 1.5.2,Python 2.x作为主流版本已经持续了很多年。本书是基 于Python 3.6的,并在P...

用tensorflow实现弹性网络回归算法

本文实例为大家分享了tensorflow实现弹性网络回归算法,供大家参考,具体内容如下 python代码: #用tensorflow实现弹性网络算法(多变量) #使用鸢尾花数据集,...

python读取注册表中值的方法

在Python的标准库中,_winreg.pyd可以操作Windows的注册表,另外第三方的win32库封装了大量的Windows API,使用起来也很方便。不过这里介绍的是使用_win...

Python读取键盘输入的2种方法

Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘。如下: 1.raw_input 2.input raw_input函数 raw_input() 函数从标准输入...

Python3按一定数据位数格式处理bin文件的方法

Python3按一定数据位数格式处理bin文件的方法

因为研究生阶段经常用MATLAB作图,处理数据,但是MATLAB太过于庞大,不方便,就想用python处理。 问题:我们通常处理的最原始的数据是bin文件,打开后如下所示,是按16进制形...