3

我需要生成一个类,该类将模仿另一个类的方法集,并通过代理表现得像后者。例如,IfBase是要模仿Deleguate的类,是需要充当Basethen 的类:

b = Base(args)
b.any_function()

严格等价于

d = Deleguate(b)
d.any_function()

如果Deleguate使用 中已存在的函数Base,则不会被覆盖。这是您对继承和方法覆盖所期望的那种行为。在我正在处理的项目的上下文中,继承不是一个选项(除其他限制外,我无权访问工厂代码)。这就是让事情变得复杂的原因。

因此,我决定编写一个“代理”装饰器:

import inspect

def proxy(bridge, target):
    def proxyfy(cls):
        for _, func in inspect.getmembers(target, predicate=inspect.ismethod):
            fname = func.__name__
            if fname in cls.__dict__:
                print 'ignoring %s.%s' % (cls, fname)
                continue
            print 'adding %s.%s' % (cls, fname)
            def proxy_func(self, *args, **kwargs):
                print 'calling %s.%s.%s' % (cls, bridge, fname)
                bridge_member = getattr(self, bridge)
                return getattr(bridge_member, fname)(*args, **kwargs)
            setattr(cls, fname, proxy_func)
        return cls
    return proxyfy

class Base(object):
    def __init__(self, i):
        self._i = i

    def __bar(self):
        print 0

    def foo(self):
        print self._i

    def foo2(self):
        print 2 * self._i


@proxy('_proxy', Base)
class Deleguate(object):
    def __init__(self, base):
        self._proxy = base

    def foo2(self):
        print 4 * self._proxy._i

d = Deleguate(Base(1))
d.__bar() # d._proxy.__bar()
d.foo()   # d._proxy.foo()
d.foo2()  # d.foo2()

我得到以下输出:

adding <class '__main__.Deleguate'>.__bar
ignoring <class '__main__.Deleguate'>.__init__
adding <class '__main__.Deleguate'>.foo
ignoring <class '__main__.Deleguate'>.foo2
calling <class '__main__.Deleguate'>._proxy.foo2
2
calling <class '__main__.Deleguate'>._proxy.foo2
2
4

我认为这setattr(cls, fname, proxy_func)会分配一个新的闭包,但是在每个循环步骤中都会覆盖参数,并且只foo2保留最后一个函数的参数。Deleguate因此调用使用参数的任何“生成”函数foo2......

为什么闭包参数被覆盖?有没有办法生成那种代理代码?预期的输出是:

adding <class '__main__.Deleguate'>.__bar
ignoring <class '__main__.Deleguate'>.__init__
adding <class '__main__.Deleguate'>.foo
ignoring <class '__main__.Deleguate'>.foo2
calling <class '__main__.Deleguate'>._proxy.__bar
0
calling <class '__main__.Deleguate'>._proxy.foo
1
4
4

1 回答 1

0

函数创建闭包,循环不会。变量名fname 是 中的局部变量proxyfy。嵌套函数proxy_func引用此局部变量。但是在调用嵌套函数时,for-loop

    for _, func in inspect.getmembers(target, predicate=inspect.ismethod):

已经完成,并且局部变量fname在循环结束时引用了它的最后一个值,恰好是'foo2'. 因此,无论您调用什么方法,每个方法proxy_func最终都会调用foo2.

要将不同的值绑定fname到 each proxy_func,您可以使用bname带有默认值的新关键字参数。默认值在定义时绑定到函数,而不是在函数运行时绑定。所以如果使用

    for bname, func in inspect.getmembers(target, predicate=inspect.ismethod):

并将其bname用作默认值:

        def proxy_func(self, bname=bname, *args, **kwargs):

然后每个proxy_func人都会调用相应的bname.

因此,只需对您的代码进行最少的更改,您就可以添加一个具有默认值的关键字参数proxy_func来记住当前方法名称:

def proxy(bridge, target):
    def proxyfy(cls):
        for bname, func in inspect.getmembers(target, predicate=inspect.ismethod):
            fname = func.__name__
            if fname in cls.__dict__:
                print 'ignoring %s.%s' % (cls, fname)
                continue
            print 'adding %s.%s' % (cls, fname)
            def proxy_func(self, bname=bname, *args, **kwargs):
                print 'calling %s.%s.%s' % (cls, bridge, bname)
                bridge_member = getattr(self, bridge)
                return getattr(bridge_member, bname)(*args, **kwargs)
            setattr(cls, fname, proxy_func)
        return cls
    return proxyfy

但是,我认为使用__getattr__可能更容易:

def proxy(bridge):
    def proxyfy(cls):
        def __getattr__(self, attr):
            target = getattr(self, bridge)
            if attr.startswith('__') and not attr.endswith('__'):
                # unmangle
                attr = '_{}{}'.format(type(target).__name__, attr)
            return getattr(target, attr)
        setattr(cls, '__getattr__', __getattr__)
        return cls
    return proxyfy

这是一个可运行的示例:

import inspect

def proxy(bridge, target):
    def proxyfy(cls):
        for bname, func in inspect.getmembers(target, predicate=inspect.ismethod):
            fname = func.__name__
            if fname in cls.__dict__:
                print 'ignoring %s.%s' % (cls, fname)
                continue
            print 'adding %s.%s' % (cls, fname)
            def proxy_func(self, bname=bname, *args, **kwargs):
                print 'calling %s.%s.%s' % (cls, bridge, bname)
                bridge_member = getattr(self, bridge)
                return getattr(bridge_member, bname)(*args, **kwargs)
            setattr(cls, fname, proxy_func)
        return cls
    return proxyfy

def proxy(bridge):
    def proxyfy(cls):
        def __getattr__(self, attr):
            target = getattr(self, bridge)
            if attr.startswith('__') and not attr.endswith('__'):
                # unmangle
                attr = '_{}{}'.format(type(target).__name__, attr)
            return getattr(target, attr)
        setattr(cls, '__getattr__', __getattr__)
        return cls
    return proxyfy

class Base(object):
    def __init__(self, i):
        self._i = i

    def __bar(self):
        print 0

    def foo(self):
        print self._i

    def foo2(self):
        print 2 * self._i


# @proxy('_proxy', Base)
@proxy('_proxy')
class Delegate(object):
    def __init__(self, base):
        self._proxy = base

    def foo2(self):
        print 4 * self._proxy._i

d = Delegate(Base(1))
d.__bar() # d._proxy.__bar()
d.foo()   # d._proxy.foo()
d.foo2()  # d.foo2()
于 2013-10-26T14:21:33.033 回答