Welcome, guest | Sign In | My Account | Store | Cart

There is classical wrapper on Python language. If you have only object and can't change object generation you can use this class.

Python, 20 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import types

class Wrapper(object):
    def __init__(self,obj):
        self._obj = obj
    
    def __getattr__(self, attr):
        
        if hasattr(self._obj, attr):
            attr_value = getattr(self._obj,attr)
            
            if isinstance(attr_value,types.MethodType):
                def callable(*args, **kwargs):
                    return attr_value(*args, **kwargs)
                return callable
            else:
                return attr_value
            
        else:
            raise AttributeError

Example usage:

class AddMethod(Wrapper):
    def bar(self):
        print "Call 'bar' method"


class A(object):
    def __init__(self,value):
        self.value = value

    def foo(self,f1,f2="str"):
        print "Call: ",self.foo," args: (",f1,f2,")"


wrapped = AddMethod(A("object value"))

wrapped.foo(2,3)
wrapped.bar()
print wrapped.value

Output: Call: <bound method A.foo of <__main__.A object at 0xb7f2bc4c>> args: ( 2 3 ) Call 'bar' method object value