Overloading and wrapping method of field of parent class in python
<p>For example I have something like this:</p>

<pre><code>class A(object):
    def __init__(self):
        pass

    def foo(self, a, b, c):
        return a + b + c


class B(object):
    def __init__(self):
        self.b = A()


def wrapper_func(func):

    def wrapper(self, *args, **kwargs):
        return func(self, a=3, *args, **kwargs)

    return wrapper


class C(B):
    def __init__(self):
        pass

    @wrapper_func
    def ???
</code></pre>

<p>Is it possible to some how overload and then wrap method <code>foo</code> of the field of parent <code>B</code> class in python without inherits from class <code>A</code>? I need the wrapper indeed because I have the different methods with same arguments, but in the same time I have to save original class B methods native (besides overloading).</p>

<p>Initialize <code>C</code>'s parent class using <code>super</code> and then pass all the parameters to the <code>foo</code> method of the composed class instance <code>A()</code> via the <em>inherited</em> attribute <code>b</code> of the class <code>C</code>:</p>

<pre><code>def wrapper_func(func):
    def wrapper(self, *args, **kwargs):
        kwargs['a'] = 3
        return func(self, *args, **kwargs)
    return wrapper


class C(B):
    def __init__(self):
        super(C, self).__init__()

    @wrapper_func
    def bar(self, *args, **kwargs):
        return self.b.foo(*args, **kwargs) # access foo via attribute b
</code></pre>

<p><em>Trial:</em></p>

<pre><code>c = C()
print(c.bar(a=1, b=2, c=3))
# 8  -&gt; 3+2+3
</code></pre>

<hr>

<p>To make the call to the decorated function via <code>c.b.foo</code>, <em>patch</em> the <code>c.b.foo</code> method with the new <code>bar</code> method:</p>

<pre><code>class C(B):
    def __init__(self):
        super(C, self).__init__()
        self._b_foo = self.b.foo
        self.b.foo = self.bar

    @wrapper_func
    def bar(self, *args, **kwargs):
        return self._b_foo(*args, **kwargs) 
</code></pre>

<p><em>Trial:</em></p>

<pre><code>c = C()
print(c.b.foo(a=1, b=2, c=3))
# 8  -&gt; 3+2+3
</code></pre>

python overloading wrapper