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

相关文章

使用Python和Scribus创建一个RGB立方体的方法

使用Python和Scribus创建一个RGB立方体的方法

使用 Scribus 的 Python 脚本编写器功能,开发一个显示 RGB 色谱的 3D 立方体。 当我决定这个夏天要玩色彩游戏时,我想到通常色彩都是在色轮上描绘的。这些色彩通常都是使...

Python3.6笔记之将程序运行结果输出到文件的方法

Python3.6笔记之将程序运行结果输出到文件的方法

新建py文件,在里面写入Python代码,代码的功能是打印10次“Hello!”,将代码文件保存到桌面上: 在命令行中运行Python脚本,并将运行结果保存到文件中: (在此之前,要确...

pandas数据集的端到端处理

1. 数据集基本信息 df = pd.read_csv() df.head():前五行; df.info(): rangeindex:行索引; data columns:列索引...

Python WXPY实现微信监控报警功能的代码

Python WXPY实现微信监控报警功能的代码

概述: 本文主要分享一下博主在学习wxpy 的过程中开发的一个小程序。博主在最近有一个监控报警的需求需要完成,然后刚好在学习wxpy 这个东西,因此很巧妙的将工作和学习联系在一起。 博文...

pymysql模块的使用(增删改查)详解

一、pymysql的下载和使用 之前我们都是通过MySQL自带的命令行客户端工具mysql来操作数据库,那如何在python程序中操作数据库呢?这就用到了pymysql模块,该模块本质...