"parent" in a class __init__ def?
bruno at modulix
onurb at xiludom.gro
Mon Jun 12 05:01:24 EDT 2006
Ray Schumacher wrote:
> What is the feeling on using "parent" in a class definition
"parent" is just a name. What is the semantic for this name ? Parent
class (ie: superclass) ? Container ? Else ?
> that class
> methods
Takes care, "class method" has a very defined meaning in Python - a
class method is a method that takes the class object - not the instance
- as first param.
> can refer to, vs. some other organization ?
> Should all relevant objects/vars just be passed into the method as needed?
There's no absolute rule about this - at most some guidelines :
- What constitutes the state of an object should be an attribute of the
object.
- What is not part of the state and is only used for a given operation
should be passed as param.
> It seems like including "parent" in the class def is just like a class
> variable,
Here again, "class variable" has a well defined meaning in Python: it's
an attribute of the class object itself, that is shared by all instances
of the class.
> which most do not recommend.
>
> An example:
> class LXSerial:
do yourself a favour : use new-style classes whenever possible.
> def __init__(self, parent, debug=False):
> ...
> def connect(self, port, baud=9600, ptimeout=10):
> if self.debug:
> self.connectedPort = StringIO.StringIO(':A#')
> else:
> if self.parent.model=='LX200GPS': ptimeout = 240
> ...
We still don't know what's the semantic for this 'parent'. But anyway,
having this test on self.parent.model smells of a design error. If the
timeout value depends on the 'parent' object, then it's clearly a
responsability of this parent object to know that value. Your code here
should read:
def connect(self, ....)
# ...
ptimeout = self.parent.timeout
# ...
You may also want to have a look at the strategy pattern, to avoid
cluttering your code with "if self.debug"...
wrt/ your original question, I don't see how one could give a sound
answer without knowing more about this "parent" object and it's
relationship with the LXSerial class/instance of.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list