Suggestions for good programming practices?

Max M maxm at mxm.dk
Tue Jun 25 11:04:42 EDT 2002


Jeff Epler wrote:

>>class myData:
>>   def __init__ (self, foo, bar):
>>      self.foo = foo
>>      self.bar = bar
>>
>>you've added quite a bit of functionality.  First, the code becomes a 
>>little more self-documenting.  "power = ckt.volts * ckt.amps" is a lot 
>>easier to read and understand than "power = ckt[0] * ckt[1]".
> 
> 
> (the following applies most obviously to modern versions of python.  I
> use subclassing of builtin objects, __slots__ and zip().  Even so, the
> myStruct class is useful in any version of Python back to at least 1.5,
> if you make myStruct a regular class, and include a definition
> of zip())
> 
> You can do even better (lower memory overhead) with
>     class myData(object):
> 	__slots__ = ['foo', 'bar']
>         def __init__ (self, foo, bar):
>             self.foo = foo
>             self.bar = bar


You can also make it even more general:

class MyData:

     def __init__(self, **args):
         self.__dict__.update(args)

d = MyData(firstName='Max M', lastName='Rasmussen')

print d.firstName, d.lastName

 >>> Max M Rasmussen


regards Max M




More information about the Python-list mailing list