如何使用元类添加方法

Knu*_*set 8 python metaclass

如何使用元类向类中添加实例方法(是的,我需要使用元类)?以下类型的工作,但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'
Run Code Online (Sandbox Code Playgroud)

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

dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")
Run Code Online (Sandbox Code Playgroud)

还有types.MethodType,但我需要一个尚未使用的实例.我在这里错过了吗?

Aar*_*paa 15

尝试动态扩展基础,以便您可以利用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
Run Code Online (Sandbox Code Playgroud)

  • 如果我想创建几个引用'bar'实现的方法怎么办? (2认同)