如何使用元类向类添加实例方法(是的,我确实需要使用元类)?以下类型有效,但 func_name 仍为“foo”:

def bar(self):
    print "bar"

class MetaFoo(type):
    def __new__(cls, name, bases, dict):
        dict["foobar"] = bar
        return type(name, bases, dict)

class Foo(object):
    __metaclass__ = MetaFoo

>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'

我的问题是,某些库代码实际上使用了 func_name,但后来无法找到 Foo 实例的“bar”方法。我可以做:

dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")

还有 types.MethodType,但我需要一个尚不存在的实例才能使用它。我在这里错过了什么吗?

有帮助吗?

解决方案

尝试动态扩展基础,这样您就可以利用 mro,并且这些方法是实际方法:

class Parent(object):
    def bar(self):
        print "bar"

class MetaFoo(type):
    def __new__(cls, name, bases, dict):
        return type(name, (Parent,) + bases, dict)

class Foo(object):
    __metaclass__ = MetaFoo

if __name__ == "__main__":
    f = Foo()
    f.bar()
    print f.bar.func_name

其他提示

我想你想做的是这样的:

>>> class Foo():
...   def __init__(self, x):
...     self.x = x
... 
>>> def bar(self):
...   print 'bar:', self.x
... 
>>> bar.func_name = 'foobar'
>>> Foo.foobar = bar
>>> f = Foo(12)
>>> f.foobar()
bar: 12
>>> f.foobar.func_name
'foobar'

现在你可以自由通过了 Foos 到一个期望的库 Foo 具有名为的方法的实例 foobar.

不幸的是,(1)我不知道如何使用元类,(2)我不确定我是否正确阅读了你的问题,但我希望这会有所帮助。

注意 func_name 仅在 Python 2.4 及更高版本中可赋值。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top