为什么在Python2.x中,带有参数的object.uuuu new_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;?
为什么以下代码在Python2.x中运行良好,而在Python3.3+中运行不好:为什么在Python2.x中,带有参数的object.uuuu new_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;?,python,python-3.3,python-2.x,Python,Python 3.3,Python 2.x,为什么以下代码在Python2.x中运行良好,而在Python3.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__
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)
(,1)
Python 3.1.5输出:
__main__:3: DeprecationWarning: object.__new__() takes no parameters
<__main__.TestB object at 0x7f2f69db8f10> 1
<__main__.TestB object at 0xcda690> 1
\uuuuu main\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
1.
Python 3.2.3和3.2.5输出:
__main__:3: DeprecationWarning: object.__new__() takes no parameters
<__main__.TestB object at 0x7f2f69db8f10> 1
<__main__.TestB object at 0xcda690> 1
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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第3行,新__
TypeError:对象()不接受任何参数
对象。\uuuuu new\uuuu
总是忽略额外的参数,并且至少从Python 2.6开始发出了一个弃用警告
您在2.7和3.2中没有看到弃用警告的原因是,自2.7和3.2以来弃用警告已被删除;如果使用python-Wd
或PYTHONWARNINGS=default
则会看到警告
在Python 3.3中,弃用警告
被转换为错误
编写代码(在任何版本的Python中)的正确方法是吞下TestA中的额外参数
class TestA(object):
def __new__(cls, e):
return super(TestA, cls).__new__(TestB)
由于TestB
是从TestA
派生出来的,因此额外的参数。您可以将uu init_u_uu函数移动到TestA,如下所示:
class TestA(object):
def __new__(cls, e):
return super(TestA, cls).__new__(TestA)
def __init__(self, e):
print(self, e)
TestA(1)
注意TestB是如何不需要的
请注意,调用对象时是如何省略“e”参数的。
object类的新函数只接受一个类作为参数,重载的新函数(在本例中为TestA类)中的任何附加参数都会自动传递给传递给object的类的构造函数(uuu init_uuuuu)。uuu new_uuu(在本例中也是TestA)。相关:它的解释器输出,第一个打印,第二个对象。如果作为程序运行,则将显示一行。修好了,你确定吗?这段代码适用于Python2.7.4和Python3.2.3.For 3.2.3,工作良好,更新帖子。