繁体   English   中英

Python2和Python3:__ init__和__new__

[英]Python2 and Python3: __init__ and __new__

我已经阅读了其他问题来解释__init____new__之间的区别,但我只是不明白为什么在下面的代码中使用python 2 out:

init

和Python3:

new
init

示例代码:

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

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

example = ExampleClass()

要在Python 2.x中使用__new__ ,该类应该是新式类 (从object派生的类)。

super()调用与Python 3.x的调用不同。

class ExampleClass(object):  # <---
    def __new__(cls):
        print("new")
        return super(ExampleClass, cls).__new__(cls)  # <---

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM