[Tutor] dict vs several variables?

Dave Angel d at davea.name
Fri Feb 17 15:26:43 CET 2012

On 02/17/2012 09:06 AM, leam hall wrote:
> On 2/17/12, Dave Angel<d at davea.name>  wrote:
>> Real question is whether some (seldom all) of those variables are in
>> fact part of a larger concept.  If so, it makes sense to define a class
>> for them, and pass around objects of that class.  Notice it's not
>> global, it's still passed as an argument.  This can reduce your
>> parameters from 20 to maybe 6.  But make sure that the things the class
>> represents are really related.
>> Dictionaries are a built-in collection class, as are lists, sets, and
>> tuples.  But you can write your own.  An example of needing a class
>> might be to hold the coordinates of a point in space.  You make a
>> Location class, instantiate it with three arguments, and use that
>> instance for functions like
>>      move_ship(ship, newlocation)
>> DaveA
> Understood. In this case, the first half dozen variables are input and
> the rest are derived from the first ones. A class might make sense and
> though I understand them a little, not enough to make a good judgement
> on it.
> The task is to take parameters for a scuba dive; depth, gas mix, time,
> air consumption rate, and compute the O2 load, gas required, etc.
> Leam
There are two ways to think of a class.  One is to hold various related 
data, and the other is to do operations on that data.  If you just 
consider the first, then you could use a class like a dictionary whose 
keys are fixed (known at "compile time").

class MyDiver(object):
     def __init__(self, depth, gasmix, time, rate):
         self.depth = int(depth)
         self.gasmix = int(gasmix)
         self.time = datetime.datetime(time)
         self.rate  = float(rate)

Now if you want to use one such:

     sam = MyDiver(200, 20, "04/14/2011",  "3.7")
     bill = MyDiver(.....)

And if you want to fetch various items, you'd do something like:
    if sam.depth < bill.depth

instead of using   sam["depth"]  and bill["depth"]

Next thing is to decide if the functions you're describing are really 
just methods on the class

class MyDiver(object):
     def __init__( ... as before)

     def get_load(self):
         return self.gasmix/self.rate            (or whatever)

and used as     print sam.get_load()

that last could be simplified with a decorator

     def load(self):
         return self.gasmix/self.rate

now it's used as though it's a regular data attribute

     print sam.load



More information about the Tutor mailing list