理解Python中的__init__和__new__
2024-10-07 07:34:47
先来看一段代码:
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
- 执行的顺序是先
__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()
继承父类其他创建 instance 的 method ,只是单纯的执行打印。所以并没有返回一个 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()
最新文章
- 使用pip安装 cx_Oracle 模块
- 深入理解javascript--笔记
- Java基础--定时任务Timer
- jquery表单对象属性选择器
- MySQL分表自增ID解决方案(转)
- Quartus 的管脚分配
- java protected 与默认权限的区别
- Python 虚拟环境:Virtualenv
- C期未考试参考答案
- Struts2+Spring+Hibernate+Jbpm技术实现Oa(Office Automation)办公系统第一天框架搭建
- python文件操作及os模块常用命令
- Linux垃圾清理
- Nginx 参数配置相关
- GCC编译器原理(二)------编译原理一:ELF文件(2)
- ubuntu下openssh升级
- 6、DHCP
- webapck html-loader实现资源复用
- FastAdmin 自己做的插件 SQL 有一个表没有生成成功
- elasticsearch6 学习之并发控制
- 20155206 2016-2017-2 《JAVA程序设计》 第二周学习总结