元类错误:type.__init__() 需要 1 或 3 个参数
我有一个元类:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是,从 python 2.5 升级到 python 2.6 时,
type.__init__()
已更改,因此您不再需要传入cls
。因此,只需进行super
调用:另一个解决方案是完全避免
super
调用并执行此操作(尽管它不太好):并且一切都会正常工作(在 python 中) >= 2.6)。
至于为什么
type.__init__()
可以采用不同数量的参数,请查看 文档。因此,除了将其用作构造函数外,您还可以调用type(myobject)
,它将返回myobject
的类型:请参阅 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 incls
. So simply make thesuper
call:Another solution is to avoid the
super
call altogether and do this (although it's a little less nice):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 calltype(myobject)
and it will return the type ofmyobject
:See What is a metaclass in Python? for more information on metaclasses and type.