Proxy object in Python

后端 未结 3 473
我寻月下人不归
我寻月下人不归 2020-12-07 00:53

I\'m looking for way to pass method calls through from an object (wrapper) to a member variable of an object (wrappee). There are potentially many methods that need to be ex

3条回答
  •  旧巷少年郎
    2020-12-07 01:21

    A somewhat elegant solution is by creating an "attribute proxy" on the wrapper class:

    class Wrapper(object):
        def __init__(self, wrappee):
            self.wrappee = wrappee
    
        def foo(self):
            print 'foo'
    
        def __getattr__(self, attr):
            return getattr(self.wrappee, attr)
    
    
    class Wrappee(object):
        def bar(self):
            print 'bar'
    
    o2 = Wrappee()
    o1 = Wrapper(o2)
    
    o1.foo()
    o1.bar()
    

    all the magic happens on the __getattr__ method of the Wrapper class, which will try to access the method or attribute on the Wrapper instance, and if it doesn't exist, it will try on the wrapped one.

    if you try to access an attribute that doesn't exist on either classes, you will get this:

    o2.not_valid
    Traceback (most recent call last):
      File "so.py", line 26, in 
        o2.not_valid
      File "so.py", line 15, in __getattr__
        raise e
    AttributeError: 'Wrappee' object has no attribute 'not_valid'
    

提交回复
热议问题