[Tutor] best practices for where to set instance member variables
alan.gauld at btinternet.com
Sat Sep 4 10:13:45 CEST 2010
"Gregory, Matthew" <matt.gregory at oregonstate.edu> wrote
> Is there a guideline on where instance member variables should
> be set within a class? That is, is it a bad idea to set self
> within private member functions rather than returning them to
> the enclosing caller?
There is nothing really specific to OOPP its just the normal rules
of defining functions. ie they should not have side effects so far
as is possible. So retrning results to the caller is generally
The only significant difference with methods is that you can look
up attributtes of self rather than pass them as arguments. This
is different to normal functions where we prefer passing arguments
rather than using global top access varuiables outside the function
defiitioon. But otherwise its all the same rules.
> Or should I avoid calls to internal functions from other member
> functions altogether (even if they are somewhat complex)?
No! This is one of the most powerful ways of achieving reuse.
For example if you define top level methods that are implemented
almost entirely by calling lower level methods then it is easy for
a subclass to modify the top level function by overriding just the
low level methods that it needs to change. That is a very powerful
technique for minimisiong change to the external interface and
thereby maintaining the Liskov Substitution Principle.
A concrete example:
def draw(self, X, Y): pass
def erase(self): pass
Now subclasses only need to implement draw and erase
and they get move() for free.
> class Foo:
> def __init__(self, a):
> self.a = self._f1(a)
> def _f1(self, a):
> return a
This one is nearly always better.
Author of the Learn to Program web site
More information about the Tutor