Python2和Python3:__ init__和__new__

Jav*_*ero 2 python init python-2.x super python-3.x

我读过这解释之间的差异的其他问题__init____new__,但我就是不明白,为什么在与Python 2了下面的代码:

init
Run Code Online (Sandbox Code Playgroud)

和Python3:

new
init
Run Code Online (Sandbox Code Playgroud)

示例代码:

class ExampleClass():
    def __new__(cls):
        print ("new")
        return super().__new__(cls)

    def __init__(self):
        print ("init")

example = ExampleClass()
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 8

__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")
Run Code Online (Sandbox Code Playgroud)