Odd*_*ing 7 python python-3.x python-3.4
我正在将一些代码从Python 2迁移到Python 3,并且我得到了不同的行为.查看"改变了什么"的列表并未指出任何相关的差异,但可能我错过了一个重要的差异.
我尽可能地简化了我的代码以获得这个"最小错误程序":
def decorator(Type):
""" This is a class decorator. It replaces a class with a subclass which
*should be* equivalent.
The result works on Python 2.7 but not on Python 3.4. """
class FactorySubclass(Type):
""" This subclasses from the provided type, and overrides the __new__
and __init__ methods, but replaces them with exact equivalents,
so I can't see how this has any effect. """
def __new__(cls, *args, **kwargs):
# Simplified this code to do basically nothing.
# If this line is removed, it works on both versions.
return Type.__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
# Simplified this code to do basically nothing.
Type.__init__(self, *args, **kwargs)
return FactorySubclass
@decorator
class ExampleClass(object):
def __init__(self, param=3):
print("Constructed example instance")
ec = ExampleClass(param=5)
Run Code Online (Sandbox Code Playgroud)
此代码运行,并Constructed example instance在Python 2.7中打印.此代码失败,并在Python 3.4中转储堆栈跟踪.
Traceback (most recent call last):
File "mfp.py", line 31, in <module>
ec = ExampleClass(param=5)
File "mfp.py", line 16, in __new__
return Type.__new__(cls, *args, **kwargs)
TypeError: object() takes no parameters
Run Code Online (Sandbox Code Playgroud)
通常这个错误意味着某人拼写错误__init__(因此构造函数参数绕过相关类并被赋予无object参数构造函数,但这似乎不是这种情况.
哦,作为事后的想法,我确认,是的,paramPython 2.7中的值为5.
2to3 给它一个清洁的健康状况.
请给我一个指向Python 3中的更改的指针,该更改将使此代码无效,因此我可能会阅读更多相关内容.
你的问题里已经有了答案:
通常,此错误意味着 [...] 构造函数参数被赋予对象的无参数构造函数 [...]
要修复此问题,请将装饰器更改为仅添加__init__and__new__如果传入的Type方法具有这些方法。
| 归档时间: |
|
| 查看次数: |
6567 次 |
| 最近记录: |