先来看一段代码:

class A(object):  # -> don't forget the object specified as base

    def __new__(cls):
print ("A. __new__ called")
return super().__new__(cls) def __init__(self):
print ("A. __init__ called") A()

输出结果:

A. __new__ called
A. __init__ called
  1. 执行的顺序是先__new____init__。因为函数__new__在我们调用类的时候会被自动调用,并且返回 instance__init__,也就是__init__中的 self

再来看一段代码:

class A(object):

    def __new__(cls):
print ("A.__new__ called") def __init__(self):
print ("A.__init__ called") # -> is actually never called print (A())

输出结果:

A.__new__ called
None

这里__init__并没有被调用。这是因为与之前不同,这次__new__ override 了父类的__new__之后,没有使用super()继承父类其他创建 instancemethod ,只是单纯的执行打印。所以并没有返回一个 instance__init__self。所以返回None

再来看如果在__new__中加入return功能会如何:

class A(object):
def __new__(cls):
print ("A. __new__ was called")
return 29 print (A())

输出结果是:

A.__new__ called
29

得用__new__函数,我们可以在创建类的 instance 的时候返回其他类型的 instance

class Sample(object):

    def __str__(self):
return "A returned an instance of Sample()" class A(object): def __new__(cls):
return Sample() print (A())

输出结果:

A returned an instance of Sample()

最新文章

  1. 使用pip安装 cx_Oracle 模块
  2. 深入理解javascript--笔记
  3. Java基础--定时任务Timer
  4. jquery表单对象属性选择器
  5. MySQL分表自增ID解决方案(转)
  6. Quartus 的管脚分配
  7. java protected 与默认权限的区别
  8. Python 虚拟环境:Virtualenv
  9. C期未考试参考答案
  10. Struts2+Spring+Hibernate+Jbpm技术实现Oa(Office Automation)办公系统第一天框架搭建
  11. python文件操作及os模块常用命令
  12. Linux垃圾清理
  13. Nginx 参数配置相关
  14. GCC编译器原理(二)------编译原理一:ELF文件(2)
  15. ubuntu下openssh升级
  16. 6、DHCP
  17. webapck html-loader实现资源复用
  18. FastAdmin 自己做的插件 SQL 有一个表没有生成成功
  19. elasticsearch6 学习之并发控制
  20. 20155206 2016-2017-2 《JAVA程序设计》 第二周学习总结

热门文章

  1. 一文学会Go - 2 数据结构与算法实践篇
  2. IDEA无法导入HttpServlet包解决方法
  3. python string_3 end 内建函数详解
  4. idea中创建maven格式的文件方法
  5. Centos7安装protobuf3.6.1
  6. java版微信支付/查询/撤销
  7. spring cloud gateway自定义过滤器
  8. [Python3] 002 Python3 中常用的命名规则
  9. 打印Java main参数
  10. go & log