從問題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