__call__类似C++中function object。可以把对象当做函数使用。

示例代码如下:

class Animal:def __init__(self, name, legs):self.name = nameself.legs = legsself.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 {0}'.format(self.name)cow = Animal('king', 4)
dog = Animal('flopp', 4)
print('We have 2 animals a cow named {0} and dog named {1}, \
both have {2} legs.'.format(cow.name, dog.name, cow.legs))print(cow)
print(dog)cow('gras')
print(cow.stomach)dog('bone')
dog('beef')
print(dog.stomach)print(cow.poop())
print(cow.stomach)

该代码片段的输出:

We have 2 animals a cow named king and dog named flopp, both have 4 legs.
A animal named king
A animal named flopp
['gras']
['bone', 'beef']
gras
[]

__new__是一个静态函数,并且至少需要传递一个参数cls。cls表示需要实例化的类。此参数在实例化时由Python解释器自动提供。另外,实例化对象时,__new__在__init__方法之前调用。有个比较形象化的比喻:__new__方法就是前期的原材料购买环节,__init__方法就是在有原材料的基础上,加工、初始化商品环节。

运行以下实例代码能加深此函数的理解:

class Demo(object): def __init__(self): print('__init__() called...')def __new__(cls, *args, **kwargs): print('__new__() - {cls}'.format(cls=cls) )return object.__new__(cls, *args, **kwargs) if __name__ == '__main__': de = Demo() 

此段代码的输出如下:

__new__() - <class '__main__.Demo'>
__init__() called...

以下是标准文档的摘录:

__call__:

Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).

__new__:

Called to create a new instance of class cls. __new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of __new__() should be the new object instance (usually an instance of cls).

__init__:

Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: super().__init__([args...]).

另外有一个值得注意的函数,该函数在把对象当做字符串使用时调用。

__str__:

Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object. The return value must be a string object.

转载于:https://www.cnblogs.com/licb/p/9685019.html

Python中的三个特殊函数相关推荐

  1. Python中的三引号的用法

    python中三引号可以将复杂的字符串进行复制: python三引号允许一个字符串跨多行,字符串中可以包含换行符.制表符以及其他特殊字符. 三引号的语法是一对连续的单引号或者双引号(通常都是成对的用) ...

  2. python中省略号三个点(...)的作用

    1ellipsis 三个点在python中的类别名称叫做ellipsis,中文意思就是省略号. type(...) <class 'ellipsis'> 2 ellipsis在Numpy或 ...

  3. python中特殊文件和特殊函数

    导入模块 模块通常为单独的.py文件,可以用import直接引用,可以作为模块的文件类型有.py..pyo..pyc..pyd..so..dll在导入模块时,解释器做以下工作: 已导入模块的名称创建新 ...

  4. Python中的三个基本知识点

    1. 引言 Python被称为易于使用和灵活多变的编程语言,有很多技巧可以用来使我们编写的代码更漂亮,更简洁.无论您是Python新手还是有多年的编程经验,学习更多的编程技巧往往可以提升工作效率. 闲 ...

  5. python三引号怎么打出来_请问python中的三引号怎么打啊?小白求助

    第一中方法比较简单,直接使用三个反斜杠进行转义,也就是: print("\"\"\"");因为\"代表一个引号,那么连续三个\"自 ...

  6. Python中的三引号''' '''的用法

    链接:https://blog.csdn.net/GreenHandCGL/article/details/79703863

  7. python中不同类型的数据不能相互运算_Python第三课——数据类型与运算(2)

    hello大家好,我是你们的小蒟蒻鸭,终于终于有时间写博客了(虽然刚开始期末复习),真的非常非常抱歉,拖更太厉害了.反正还有一个月不到小蒟蒻就要放暑假了!!!(激动.jpg),蒟蒻保证会一周两篇,绝不 ...

  8. python请输入_python中的三种输入方式

    python中的三种输入方式 python2.X python2.x中以下三个函数都支持: raw_input() input() sys.stdin.readline() raw_input( )将 ...

  9. python选择语句是什么语句_Python语言中的三种选择语句

    本文将详细介绍Python语言中的三种选择语句:if语句,if/else语句和if/elif/else语句.对于每种语句,我们都提供了相应的流程图.与此同时,我们给出许多简单的示例程序,以帮助读者加深 ...

最新文章

  1. python 单词发音-在python中的单词上拆分语音音频文件
  2. python函数的两种嵌套方法
  3. 国外计算机科学英语演讲,2014年暨大英语演讲大赛圆满落幕
  4. 上传漏洞学习——upload-labs 闯关(一)
  5. 网站遭遇CC及DDOS攻击紧急处理方案
  6. inherits java_JAVA内部类和组合的区别
  7. 用JavaScript往DIV动态添加内容
  8. SpringBoot配置swagger2(亲测有效,如果没有配置成功,欢迎在下方留言)
  9. 物联网设备获取北京时间、年月日、星期几,GMT格林威治标准时间转换为北京时间,授时api Fiddler抓包调试
  10. 由李飞飞领导,斯坦福以人为本AI学院正式成立,比尔·盖茨来捧场
  11. 吉大20春学期计算机系统结构在线作业一,吉大20春学期《计算机原理及系统结构》在线作业一【奥鹏百分答案】...
  12. Python爬虫编程实践 Task02
  13. 解决Mac按列浏览图加载慢的问题
  14. STL总结之list
  15. python找不到sys模块_在本地目录中找不到模块,存在于sys.path中
  16. xrd连续扫描和步进扫描_多晶XRD步进扫描与连续扫描介绍
  17. 为什么电脑浏览器打不开网页但微信可以登陆
  18. 读书202101『股票大作手回忆录』
  19. 华为的人力资源管理揭秘
  20. 欢乐颂之鸿蒙系统,化神前辈传要诀 《镇魔曲》鸿蒙指引全新上线

热门文章

  1. 升级! Facebook 模型全部迁移至 PyTorch 框架
  2. 最新!李飞飞提出深度进化强化学习新框架
  3. jsp页面适应手机屏幕_HTML5之页面缩放 viewport
  4. 面向小姐姐的编程——JAVA面向对象之继承(三)
  5. 深度学习中的损失函数总结以及Center Loss函数笔记
  6. vue父子组件生命周期执行顺序_关于Vue组件的生命周期及执行顺序
  7. python traceback_Python 列表操作,节后大放送
  8. linux接收数据并保存到环形缓冲区,自定义print函数缓存打印数据到环形缓冲区...
  9. 为什么说在国内考CISP比CISSP要好?
  10. Kali Linux 从入门到精通(八)-主动信息收集