元类错误:type.__init__() 需要 1 或 3 个参数

发布于 2025-01-04 12:45:41 字数 536 浏览 5 评论 0原文

我有一个元类:

class MyMeta(type):
    def __init__(cls, name, bases, dct):
        # Do something
        ...

        return super(MyMeta, cls).__init__(cls, name, bases, dct)

和一个类:

class MyClass(object):
    __metaclass__ = MyMeta

当我使用这些时,我收到以下错误:

TypeError: Error when calling the metaclass bases
    type.__init__() takes 1 or 3 arguments

问题是什么,为什么 type.__init__() 采用精确可变数量的参数?

I have a metaclass:

class MyMeta(type):
    def __init__(cls, name, bases, dct):
        # Do something
        ...

        return super(MyMeta, cls).__init__(cls, name, bases, dct)

and a class:

class MyClass(object):
    __metaclass__ = MyMeta

When I use these I get the following error:

TypeError: Error when calling the metaclass bases
    type.__init__() takes 1 or 3 arguments

What's the problem, and why does type.__init__() take a precisely variable number of arguments?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北风几吹夏 2025-01-11 12:45:41

问题是,从 python 2.5 升级到 python 2.6 时,type.__init__() 已更改,因此您不再需要传入 cls。因此,只需进行 super 调用:

return super(MyMeta, cls).__init__(name, bases, dct)

另一个解决方案是完全避免 super 调用并执行此操作(尽管它不太好):

return type.__init__(cls, name, bases, dct)

并且一切都会正常工作(在 python 中) >= 2.6)。

至于为什么 type.__init__() 可以采用不同数量的参数,请查看 文档。因此,除了将其用作构造函数外,您还可以调用 type(myobject) ,它将返回 myobject 的类型:

>>> number = 1
>>> type(number)
<type 'int'>
>>> type('my string')
<type 'str'>

请参阅 Python 中的元类是什么? 有关元类和类型的更多信息。

The problem is that in the upgrade from python 2.5 to python 2.6 type.__init__() was changed so that you are no longer required to pass in cls. So simply make the super call:

return super(MyMeta, cls).__init__(name, bases, dct)

Another solution is to avoid the super call altogether and do this (although it's a little less nice):

return type.__init__(cls, name, bases, dct)

And everything will work fine (in python >= 2.6).

As to why type.__init__() can take differing numbers of arguments, check out the documentation. It's so that as well as using it as a constructor, you can call type(myobject) and it will return the type of myobject:

>>> number = 1
>>> type(number)
<type 'int'>
>>> type('my string')
<type 'str'>

See What is a metaclass in Python? for more information on metaclasses and type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文