【发布时间】:2013-10-17 03:05:43
【问题描述】:
来自问题Why does or rather how does object.__new__ work differently in these two cases
作者对原因不感兴趣,而对方法感兴趣。
我非常想知道为什么,尤其是:
为什么
object.__init__不打印参数而不是object.__new__ (in testclass1)为什么没有为 testclass3 引发错误? (因为它除了 self 不需要任何参数)
代码
>>> 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 对python 源代码的评论?他们决定不在某些情况下引发错误以允许仅定义
__init__或__new__之一。否则你总是不得不重新定义它们,即使它们是无操作的。 -
我不明白:我只定义了 init,它不接受任何参数(显然除了 self),我将一个参数传递给 新的,为什么不报错?
标签: python object types constructor