Python proxy class

こ雲淡風輕ζ 提交于 2019-12-06 07:26:49

I would not explicitly copy the methods of the wrapped class. You can use the magic method __getattr__ to control what happens when you call something on the proxy object, including decorating it as you like; __getattr__ has to return a callable object, so you can make that callable do whatever you need to (in addition to calling the original method).

I have included an example below.

class A:
    def foo(self): return 42
    def bar(self, n): return n + 5
    def baz(self, m, n): return m ** n

class Proxy:
    def __init__(self, proxied_object):
        self.__proxied = proxied_object

    def __getattr__(self, attr):
        def wrapped_method(*args, **kwargs):
            print("The method {} is executing.".format(attr))
            result = getattr(self.__proxied, attr)(*args, **kwargs)
            print("The result was {}.".format(result))
            return result    
        return wrapped_method

proxy = Proxy(A())
proxy.foo()
proxy.bar(10)
proxy.baz(2, 10)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!