从问题Why does or rather how does object.__new__ work differently in these two cases为什么在这三种情况下
笔者是不感兴趣的原因,而是在如何不同对象.__ new__工作。
我就非常想知道为什么,特别是:
为什么不是
object.__init__
不带印刷的,而不是object.__new__ (in testclass1)
参数,为什么不会引发错误的testclass3? (因为它没有超越自我其他参数)
代码
>>> class testclass1(object):
... pass
...
>>> class testclass2(object):
... def __init__(self,param):
... pass
...
>>> a = object.__new__(testclass1, 56)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object.__new__() takes no parameters
>>> b = object.__new__(testclass2, 56)
>>> b
<__main__.testclass2 object at 0x276a5d0>
>>> class testclass3(object):
... def __init__(self):
... pass
...
>>> c = object.__new__(testclass3, 56)
>>> c
<__main__.testclass3 object at 0x276a790>
>>> c1 = object.__new__(testclass3)
>>> c1
<__main__.testclass3 object at 0x276a810>
你读过[this](http://hg.python.org/cpython/file/44ed0cd3dc6d/Objects/typeobject.c#l2818)对Python源代码的评论吗?他们决定在某些情况下不会提出错误,只允许定义一个'__init__'或'__new__'。否则,即使它们没有运行,你也必须重新定义它们。 – Bakuriu
我不明白:我只定义__init__,它不需要任何参数(除了明显的自我),我传递给__new__的参数,为什么它不会引发错误? – ychaouche