Python2 and Python3: __init__ and __new__

…衆ロ難τιáo~ 提交于 2019-12-24 03:47:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!