以下代码会产生错误:
class FooMeta(type):
def __new__(mcl, classname, bases, classdict):
return type.__new__(mcl, classname, bases, dict())
def __init__(cls, name, bases, classdict):
super(FooMeta, cls).__init__(name, bases, classdict)
d = dict()
for key, item in classdict.items():
if key.startswith("_"):
setattr(cls, key, item)
else:
d[key] = item
setattr(cls, '_items', d)
class Foo(object):
__metaclass__ = FooMeta
class Passing(Foo):
def __init__(self, *args, **kw):
pass
class Failing(Foo):
def __new__(cls, *args, **kw):
return super(Failing, cls).__new__(cls)
def __init__(self, *args, **kw):
pass
fail = Failing()
错误是
Traceback (most recent call last):
File ".../FooMeta,py", line 30, in <module>
fail = Failing()
TypeError: unbound method __new__() must be called with Failing instance as first argument (got FooMeta instance instead)
__new__
从元类调用时,调用方式似乎有所不同。
1)有人知道为什么会这样吗?2)有什么办法可以解决吗?