Using a class as a structure/container

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Feb 6 08:18:39 CET 2008


En Wed, 06 Feb 2008 00:59:48 -0200, <david.car7 at gmail.com> escribi�:

> Is it appropriate to use a class as a simple container in order to
> access attributes using a series of dot operators?  Is their a more
> Pythonic way of doing this?  For instance, I have a "container" class
> which is never instantiated directly, but only through another class.
> Access to certain attributes would be something like:
>
>   main_class.a.b.x
>
> where row and v1 are instances of the container class which are
> instantianted by main_class.  I know I can use dictionaries, but this
> syntax is a little clearer as long as the number of dot operators is
> not too lengthy.  Some code would be something like:
>
> class container(object):
>     def __init__(self):
>         pass

You can omit the __init__ method if it's empty

> class main_class(object):
>     def __init__(self):
>         self.a = container()
>         settatr(self.a, 'b', container())
>         settatr(self.a.b, 'x', 2)

Usually written as:
         self.a.b = container()
         self.a.b.x = 2

Nothing in the language forbids doing what you do, but I'd ask if the  
attributes may be split logically between the various containers, or it is  
an artificial division and they really should be attributes of the  
main_class.
There are documentation problems too: such generic container cannot tell  
which attributes are valid or not; introspection tools cannot tell very  
much about the class; perhaps some code completion tools get confused. I  
don't like a long sequence of dots either.
Using such a deep structure you are violating the Law of Demeter "Don't  
talk to strangers" http://en.wikipedia.org/wiki/Law_of_Demeter (altough I  
don't follow it strictly, things like xobj.parent.connection.user.name  
look wrong to me)

Another problem of such generic container is that you don't get any  
meaningful information when printing it. You may find the NamedTuples  
recipe useful; look into the Python Cookbook  
http://www.activestate.com/ASPN/Python/Cookbook/ - or perhaps using this  
class:

class Record(object):
     def __init__(self, **kw):
         self.__dict__.update(kw)

     def __repr__(self):
         values = ['%s=%r' % item
                   for item in sorted(self.__dict__.iteritems())]
         return '%s(%s)' % (self.__class__.__name__, ','.join(values))

     __str__ = __repr__


x = Record(a=1, b=2.0, c="three")
print x
# output: Record(a=1,b=2.0,c='three')



-- 
Gabriel Genellina




More information about the Python-list mailing list