我读过其他问题来解释两者之间的区别__init__
and __new__
但我只是不明白为什么在下面的代码中用 python 2 输出:
init
和Python3:
new
init
示例代码:
class ExampleClass():
def __new__(cls):
print ("new")
return super().__new__(cls)
def __init__(self):
print ("init")
example = ExampleClass()
To use __new__
在 Python 2.x 中,该类应该是新式课堂(类派生自object
).
并致电super()与Python 3.x不同。
class ExampleClass(object): # <---
def __new__(cls):
print("new")
return super(ExampleClass, cls).__new__(cls) # <---
def __init__(self):
print("init")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)