Python OOP advice
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Wed Sep 17 10:08:57 EDT 2008
Ben Finney a écrit :
> Simon Hibbs <simon.hibbs at gmail.com> writes:
>
>> 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.
>
> Was it as messy as this::
>
> class ShipHull(object):
> def __init__(self, size):
> self.components = dict()
> self.size = size
>
> class ShipComponent(object):
> def __init__(self, name, hull):
> self.name = name
> self.hull = hull
>
>> I have defined a base class Component with a class member variable
>> 'hull_size' so that all components can see the hull size.
>
> It seems to me the hull is an attribute of the component, and the size
> is an attribute of the hull. Why would the hull size be a *class*
> attribute?
>
>> 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.
>
> class FixedShipComponent(ShipComponent):
> def _get_mass(self):
> return calculation_foo(self.hull.size)
> mass = property(_get_mass)
>
> def _get_cost(self):
> return calculation_bar(self.hull.size)
> cost = property(_get_cost)
>
> class PercentShipComponent(ShipComponent):
> def _get_mass(self):
> return calculation_spam(self.hull.size)
> mass = property(_get_mass)
>
> def _get_cost(self):
> return calculation_eggs(self.hull.size)
> cost = property(_get_cost)
Or use the strategy pattern (dummy example, don't have time to read your
specs !-):
class FixedMassCostStrategy(object):
def get_mass(self, hull):
return calculation_foo(hull.size)
def get_cost(self):
return calculation_bar(hull.size)
class PercentMassCostStrategy(object):
def get_mass(self, hull):
return calculation_spam(hull.size)
def get_cost(self):
return calculation_eggs(hull.size)
class ShipComponent(object):
def __init__(self, name, hull, masscost_strategy):
self.name = name
self._hull = hull # implementation detail
self._strategy = masscost_strategy
mass = property(lambda self: self._strategy.get_mass(self._hull))
cost = property(lambda self: self._strategy.get_cost(self._hull))
More information about the Python-list
mailing list