Is it better to use class variables or pass parameters?

James Stroud jstroud at ucla.edu
Wed Mar 1 21:41:30 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
> or should I pass around variable between the methods?
> 
> Flamewar........NOW!
> 
> jk, I really do want other opinions.
> 
> Thanks,
> Derek
> 

I tend to think in terms of states. If a quantity/attribute is important 
for the state of an object, then it should be an instance variable. If 
it can be calculated from the state, then it can be made a read-only 
property, etc. If it is irrelevant to the state of an object, it 
probably should belong to another object or should be a global.

Here is an example from chemistry:

densities = {'H2O' : 1.0, 'Hg' : 13.6}

class CupOfLiquid(object):
   def __init__(self, liquid, volume):
     self.liquid = liquid
     self.volume = volume
   def spill(self, spill_vol):
     newvol = self.volume - spill_vol
     if newvol < 0:
       raise SpillError, "Can't spill that much!"
     self.volume = newvol
   def get_mass(self):
     return densities[self.liquid] * self.volume
   mass = property(get_mass)

Notice that it would be quite awkward to remember the volume state of a 
CupOfLiquid instance between method calls. One would need a global to do 
this, which defeats the purpose of using classes (i.e. object 
orientation). Notice also that the value of densities is independent of 
the state of any CupOfLiquid instance, so it is a global.

As an exercise, try threading this object for evaporation. Hint, you 
might need a "lid_closed" attribute.

James



More information about the Python-list mailing list