Using a class as a structure/container

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Feb 7 07:24:13 EST 2008


david.car7 at gmail.com a écrit :
(snip)
> Thanks for the information.  The reason why I was taking this approach
> was more from a user interface perspective.  What I have is a file
> that contains certain geometric objects, lets call them geo.  Each geo
> object has 4 possible surfaces:

You mean it has one of the 4 surfaces, or it has them all ?

> ps, ss, le, te.  Each surface has
> x,y,z coordinates.  It is not known apriori if any of these surfaces
> exist in the file.  So I created a geo_reader class that is passed a
> filename in its argument list.  It then parses the file, creating a
> container class for each geo object and assigning the name geo0, geo1,
> geo2, etc... as an attribute of the geo_reader class.

You want an indexed ordered collection (ie: something like a list) here.

>  The geo_reader
> class also stores global attributes concerning the file, i.e. the
> number of geo objects,

a list handle this.

> etc...  Then for each geo container I bind
> another container class for each surface that I find for each geo
> object, i.e. the ps, ss, le, te surfaces.  Then the coordinates for
> each of the surfaces becomes an attribute of each of their
> corresponding containers. 

Err... Why don't you actually take time to write the Geo and Surface 
classes ? It will *really* save you time in the long run.

> I can also bind certain attributes to the container class to tell
> whether its a geo object or surface, etc.

You definitively want to write the appropriate classes.

>  I just didn't want the user
> to have to use the dictionary syntax like this:
> 
> x_coords = my_geo['geo0']['ps']['x']

As far as I'm concerned, I'd use a list-like interface for my_geo, ie:

   my_geo[0].ps.x

And I'd define the four surface attributes of the Geo object, default 
them to either None or a NullSurface object (whose x and y attribs have 
the None value).

> It just seems a little more natural to use the dot operator approach
> for users to interface with.

wrt/ attribute access, yes, indeed. wrt/ what is clearly an ordered 
collection, there's already a well defined interface !-)

And anyway, this doesn't mean you should not properly define your 
classes - this is no more complex than what you're doing here, and it 
will make your code *way* more readable, maintainable and usable - even 
for your users, since they'll be able to introspect your objects type, 
print the docstrings (if you write them of course), eventually use 
autocompletion (cf the rlcompleter module) etc.

>  I wasn't aware of the Law of Demeter and
> I agree with all your concerns.  I'm just not sure which one a user
> would rather interface with from the command line.  The dot operators
> are quicker to type.

Indeed. Now if you have such concern, why not go all the way ?-)

My 2 cents



More information about the Python-list mailing list