问题
I have read other questions which explain the difference between __init__
and __new__
but I just do not understand why in the following code with python 2 out:
init
and Python3:
new
init
The sample code:
class ExampleClass():
def __new__(cls):
print ("new")
return super().__new__(cls)
def __init__(self):
print ("init")
example = ExampleClass()
回答1:
To use __new__
in Python 2.x, the class should be new-style class (class derived from object
).
And call to super() is different from that of Python 3.x.
class ExampleClass(object): # <---
def __new__(cls):
print("new")
return super(ExampleClass, cls).__new__(cls) # <---
def __init__(self):
print("init")
来源:https://stackoverflow.com/questions/31772535/python2-and-python3-init-and-new