6

以下代码会产生错误:

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)有什么办法可以解决吗?

4

1 回答 1

3

如果您允许按照通常的方式设置属性:

class FooMeta(type):
    def __new__(mcl, classname, bases, classdict):
        return type.__new__(mcl, classname, bases, classdict)

并且不要摆弄它们__init__,您会看到这Failing.__new__通常是一个静态方法:

class FooMeta(type):
    def __new__(mcl, classname, bases, classdict):
        return type.__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)
                pass
            else:
                d[key] = item
        setattr(cls, '_items', d)

class Foo(object):
    __metaclass__ = FooMeta

class Failing(Foo):
    def __new__(cls, *args, **kw):
        return super(Failing, cls).__new__(cls)

    def __init__(self, *args, **kw):
        pass

print(Failing.__dict__['__new__'])
foo = Failing()

产量:

<staticmethod object at 0xb774ba94>

但是,如果您运行您发布的代码,并在末尾添加了此打印语句:

print(Failing.__dict__['__new__'])
foo = Failing()

您会看到__new__已更改为函数:

<function __new__ at 0xb747372c>

您可以通过允许像通常那样设置 classdict 中的所有属性,然后删除那些不以 开头的属性来解决此问题_

class FooMeta(type):
    def __new__(mcl, classname, bases, classdict):
        return type.__new__(mcl, classname, bases, classdict)

    def __init__(cls, name, bases, classdict):
        super(FooMeta, cls).__init__(name, bases, classdict)
        d = dict()
        for key, item in classdict.items():
            if not key.startswith("_"):
                delattr(cls, key)
                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

print(Failing.__dict__['__new__'])
foo = Failing()
于 2012-12-03T23:09:08.077 回答