• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python中有趣在__call__函数

Python中有趣在__call__函数

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python call,python call 方法,python中 call,python check call,set函数python等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。
换句话说,我们可以把这个类型的对象当作函数来使用,相当于 重载了括号运算符。

class g_dpm(object):
def __init__(self, g):
self.g = g
def __call__(self, t):
return (self.g*t**2)/2
</div>

计算地球场景的时候,我们就可以令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
[]
'''
</div>

</div>

您可能想查找下面的文章:

  • Python中str is not callable问题详解及解决办法
  • Python中有趣在__call__函数
  • python中__call__内置函数用法实例
  • Python中__call__用法实例

相关文章

  • python3实现ftp服务功能(服务端 For Linux)
  • python实现端口转发器的方法
  • 分享一下Python 开发者节省时间的10个方法
  • 使用Python发送邮件附件以定时备份MySQL的教程
  • 编写Python小程序来统计测试脚本的关键字
  • Python正则表达式实现截取成对括号的方法
  • 简单上手Python中装饰器的使用
  • Python设计模式编程中解释器模式的简单程序示例分享
  • python模块之StringIO使用示例
  • Python的Flask框架中使用Flask-SQLAlchemy管理数据库的教程

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • python操作MySQL数据库的方法分享
    • Python多线程实例教程
    • Python实现基于HTTP文件传输实例
    • 全面解析Python的While循环语句的使用方法
    • Python读写ini文件的方法
    • Python中的自定义函数学习笔记
    • c++生成dll使用python调用dll的方法
    • Python实现带百分比的进度条
    • 深入理解Python中字典的键的使用
    • Python判断直线和矩形是否相交的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有