Python OOP advice

Simon Hibbs simon.hibbs at gmail.com
Wed Sep 17 07:50:48 EDT 2008


I'm rewriting a design application for a science fiction game. in it
you design your own starships. Each component has a mass and cost, but
the mass can either be fixed or it can be expressed as a percentage of
the tonnage of the overall ship.

Orriginaly I thought I'd need to have a hull object which contains
component objects, but the component objects need access to members of
the hull object (e.g. the hull size) so that looks messy to implement.

I have defined a base class Component with a class member variable
'hull_size' so that all components can see the hull size. I've then
got two child classes called Fixed_Component and Percent _Component
that implement their mass, mass_percent and cost properties
appropriately for their type. I've also defined a Hull class which
also inherits from Component and provides methods for access to the
hull_size class variable.

I'm not sure where to go from here. One possibility is to have a Ship
object containing a list of components, but I'd need to have a way to
ensure there's only ever one hull object so maybe that shouldn't go in
the list?

I think the fact that the hull_size is a class member also means I
can't ever have an application that loads two designs at the same
time, because they'd share the same hull_size class variable. Is that
so, and is there a way round that? I suspect the inheritance model
will work fine at first, but is too rigid in the long run.

Is there a way to cleanly implement a parent-child relationship
between objects that gives child objects limited access to members of
the parent?

Simon Hibbs



More information about the Python-list mailing list