为什么在类中添加__new__方法使其抛出TypeError:object .__ new__不带参数?

时间:2018-08-30 09:21:34

标签: python class magic-methods

我有一个采用如下构造函数参数的类:

class Works:
    def __init__(self, x):
        pass

该课程效果很好;我可以打Works(5)没问题。

但是,向我的类添加__new__方法会使它停止工作,即使__new__方法除了传递其接收到的参数之外没有做任何事情:

class Breaks:
    def __new__(cls, x):
        return super().__new__(cls, x)

    def __init__(self, x):
        pass

如果我尝试创建此类的实例,则会引发异常:

>>> Breaks(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "untitled.py", line 8, in __new__
    return super().__new__(cls, x)
TypeError: object.__new__() takes no arguments

为什么这种绝对没有任何作用的__new__方法会导致我的类停止工作,又该如何解决?

0 个答案:

没有答案