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批量赋值操作实例

变量名和变量值俊发生规律的变化,利用for循环完成赋值操作。 举个例子: for i in range(1, 10): exec("t%d=i"%i) print(t1) pr...

在python中获取div的文本内容并和想定结果进行对比详解

div的内容为: <div style="background-color: rgb(255, 238, 221);" id="status" class="errors">...

Python中文件操作简明介绍

打开文件 open函数返回一个文件对象,基本语法: ●file_object = open(file_name, access_mode='r'[,buffering=-1]) file...

详解Python核心对象类型字符串

Python的字符串的特点 Python与C语言,Java语言都不一样,没有单个字符,只有一个有一个字符的字符串。 字符串对象不可修改,属于不可变类型 字符串和列表,元组都...

python利用socketserver实现并发套接字功能

python利用socketserver实现并发套接字功能

本文实现利用python的socketserver这个强大的模块实现套接字的并发,具体内容如下 目录结构如下: 测试文件请放在server_file文件夹里面 server.py...