TypeError:object() 不接受参数 - 但仅在 Python 3 中

7 投票
1 回答
6901 浏览
提问于 2025-04-30 14:42

我正在把一些代码从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)

这段代码在Python 2.7中可以运行,并打印出Constructed example instance。但在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

通常,这种错误意味着有人拼错了__init__(这样构造函数的参数就会绕过相关的类,传给object的无参数构造函数,但在这里似乎不是这种情况。

哦,顺便说一下,我确认在Python 2.7中,param的值确实是5。

2to3工具检查后也没有发现问题。

请给我指个方向,告诉我Python 3中有什么变化会导致这段代码失效,这样我可以进一步了解。

暂无标签

1 个回答

2

你在问题中其实已经有答案了:

通常这个错误意味着 [...] 构造函数的参数 [...] 被传给了没有参数的对象构造函数 [...]

要解决这个问题,你需要修改你的装饰器,只在传入的 Type__init____new__ 这两个方法时才添加它们。

撰写回答