【发布时间】:2014-07-01 14:34:17
【问题描述】:
为什么以下代码在 Python 2.x 中可以正常工作,而在 Python 3.3+ 中却不行:
class TestA(object):
def __new__(cls, e):
return super(TestA, cls).__new__(TestB, e)
class TestB(TestA):
def __init__(self, e):
print(self, e)
TestA(1)
Python 2.7.6 输出:
(<__main__.TestB object at 0x7f6303378ad0>, 1)
Python 3.1.5 输出:
__main__:3: DeprecationWarning: object.__new__() takes no parameters
<__main__.TestB object at 0x7f2f69db8f10> 1
Python 3.2.3 和 3.2.5 输出:
<__main__.TestB object at 0xcda690> 1
Python 3.3.5 和 3.4.1 输出:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __new__
TypeError: object() takes no parameters
【问题讨论】:
-
这是解释器输出,第一个打印,第二个对象。如果作为程序运行将一行。固定。
-
你确定吗?此代码适用于 Python 2.7.4 和 Python 3.2.3。
-
对于 3.2.3 工作正常,更新帖子。
标签: python python-3.3 python-2.x