【问题标题】:Python2 and Python3: __init__ and __new__Python2 和 Python3:__init__ 和 __new__
【发布时间】:2015-10-24 16:32:16
【问题描述】:

我已经阅读了其他解释 __init____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()

【问题讨论】:

  • python2 示例的语法错误

标签: python python-3.x python-2.x init super


【解决方案1】:

要在 Python 2.x 中使用__new__,类应该是new-style class(类派生自object)。

并且对super()的调用不同于Python 3.x。

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

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

【讨论】:

    猜你喜欢
    • 2016-11-26
    • 2012-08-01
    • 2018-11-11
    • 1970-01-01
    • 2011-06-19
    • 2019-10-24
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多