Proxy object in Python

后端 未结 3 478
我寻月下人不归
我寻月下人不归 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:37

    Here's another monkey-patch method. This one copies methods into the Wrapper class directly rather than the created wrapper object. The key advantage to this one is that all special methods such as __add__ will work.

    class Wrapper(object):
        def __init__(self, wrappee):
            self.wrappee = wrappee
    
        def foo(self):
            print('foo')
    
    
    def proxy_wrap(attr):
        "This method creates a proxy method that calls the wrappee's method."
        def f(self, *args):
            return getattr(self.wrappee, attr)(*args)
        return f
    
    # Don't overwrite any attributes already present
    EXCLUDE = set(dir(Wrapper))
    
    # Watch out for this one...
    EXCLUDE.add('__class__')
    
    for (attr, value) in inspect.getmembers(Wrappee, callable):
        if attr not in EXCLUDE:
            setattr(Wrapper, attr, proxy_wrap(attr))
    

    I used this to wrap numpy arrays. With Wrappee set to np.ndarray:

    import numpy as np
    
    Wrappee = np.ndarray
    
    # [The block I wrote above]
    
    wrapped = Wrapper(np.arange(10))
    

    Operations such as wrapped + 1 still work.

提交回复
热议问题