What's the correct way to access methods of a member variable in a class pointing to an object?
<p>What's the correct way to define/access methods of a member variable in a class pointing to an object?</p>

<p>For example, I have a class <code>Foo</code> that has a method <code>foo_method</code>:</p>

<pre><code>class Foo:
    def foo_method(self):
        return 'bar'
</code></pre>

<p>Now, in another class <code>Bar</code>, I'd like to store an object to this class (I do not want <code>Bar</code> to inherit <code>Foo</code>).</p>

<p>What is the correct/recommended way to define class <code>Bar</code>?</p>

<pre><code>class Bar:
    def __init__(self):
        self.foo = Foo()

# OR

class Bar:
    def __init__(self):
        self.foo = Foo()

    def bar_method(self):
        return self.foo.bar()
</code></pre>

<p>The former will allow me to use:</p>

<pre><code>x = Bar()
x.foo.foo_method()
</code></pre>

<p>But, with this I'm directly accessing methods of a member variable (strong coupling).</p>

<p>The benefits I see with this approach are:</p>

<ul>
<li>I don't have to wrap every new method that gets added to class <code>Foo</code>.</li>
<li><code>Bar</code> may contain more member variables pointing to other classes. Not 
wrapping them keeps <code>Bar</code> smaller and manageable in size.</li>
<li>The auto-completion facility from IDE (PyCharm, etc.) or IPython helps 
inspect <code>bar</code> like a menu (<code>x.foo</code>) followed by a sub-menu 
(<code>x.foo.foo_method()</code>, <code>x.bar.foobar()</code>, etc.) making it easier to develop code.</li>
<li>Functional programming look-n-feel (not sure if this a pro or con)</li>
</ul>

<p>The cons are strong coupling, not encapsulating internal details of <code>foo</code>, etc.</p>

<p>I wanted to check if this a recommended practice?
And/or if there are any guidelines related to this (kind of implementing a composite pattern)?</p>

<p>Any inputs/pointers will be highly appreciated!</p>

<p>There are no real guidelines, but if you make a <code>bar_method()</code> that explicitly calls <code>foo.bar()</code> and does nothing in between it's the exact same coupling and less convenient.</p>

<p>Python's idioms include "<a href="http://docs.python-guide.org/en/latest/writing/style/#we-are-all-responsible-users" rel="nofollow">We are all responsible users</a>" and in that case, when encapsulation does not provide you any benefit, I personally wouldn't use proxy functions. Leaving it as is results in smaller code which is easier to maintain and is more accessible. Auto-completion as you mentioned is just an added bonus.</p>

python design-patterns python-3.5 composition