Is it better to use class variables or pass parameters?
bruno at modulix
onurb at xiludom.gro
Thu Mar 2 08:39:43 EST 2006
Derek Basch wrote:
> This one has always bugged me. Is it better to just slap a "self" in
> front of any variable that will be used by more than one class method
s/class method/method/
In Python, a "class method" is a method working on the class itself (not
on a given instance).
> or should I pass around variable between the methods?
One of the first rules I learned (from experience...) was to restrict as
much as possible the scope of a variable. It usually makes code more
readable, more robust, and more modular. In fact, I sometime even pass
attributes of an object as args to a method of the same object, and/or
assign values returned from a method of an object to attributes of the
same object. This is more explicit than relying on side-effects.
So (as pointed by almost everyone in this thread...) the best criteria
here is : is this variable part of the state of an object, or is it just
a value used for a given computation ?
Note that if you find yourself passing the same huge set of variables
from method to method for a given computation, this may calls for a
refactoring... Python objects can be callable (ie function-like), so a
complex computation with lot of shared state (independant from the rest
of the object) may be best implemented as a separate temporary callable
object - which can take the calling object as a parameter if it needs to
access other attributes from it.
My 2 cents...
--
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