[Tutor] What's the correct way to define/access methods of a member variable in a class pointing to an object?
Sharad Singla
sharad1087 at gmail.com
Sat Sep 3 01:55:07 EDT 2016
Hi Pythonistas
What's the correct way to define/access methods of a member variable in a
class pointing to an object?
For example, I have a class Foo that has a method foo_method:
class Foo:
def foo_method(self):
return 'bar'
Now, in another class Bar, I'd like to store an object to this class (I do
not want Bar to inherit Foo).
What is the correct/recommended way to define class Bar?
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()
The former will allow me to use:
x = Bar()
x.foo.foo_method()
But, with this I'm directly accessing methods of a member variable (strong
coupling).
The benefits I see with this approach are:
- I don't have to wrap every new method that gets added to class Foo.
- Bar may contain more member variables pointing to other classes. Not
wrapping them keeps Bar smaller and manageable in size.
- The auto-completion facility from IDE (PyCharm, etc.) or IPython helps
inspect bar like a menu (x.foo) followed by a sub-menu (
x.foo.foo_method(), x.bar.foobar(), etc.) making it easier to develop
code.
- Functional programming look-n-feel (not sure if this a pro or con)
The cons are strong coupling, not encapsulating internal details of foo,
etc.
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)?
There may be more classes (Bat(), etc.) in future and I'd like to extend
Foo in future to store an object of these classes. Foo() is a part of a
library and my intent is to make Foo() as the entry point for the target
users (to allow them auto-completion via dotted notation) rather than
having them remember all the classes Bar(), Bat(), etc.
Any inputs/pointers will be highly appreciated!
Regards
Sharad
PS> I've posted this in SO at
http://stackoverflow.com/questions/39231932/whats-the-correct-way-to-access-methods-of-a-member-variable-in-a-class-pointin/39237874#39237874
but I'm looking for more information/ideas/thoughts/opinions on this.
More information about the Tutor
mailing list