[Tutor] class design - base classes with optional properties?

Kent Johnson kent37 at tds.net
Thu Jan 22 21:41:08 CET 2009


On Thu, Jan 22, 2009 at 3:04 PM, Marcus Goldfish <magoldfish at gmail.com> wrote:
> I'm trying to design a base class for a hierarchy.  The properties I want to
> specify for the base class depend on the values of other properties of the
> base class.  For instance, in this toy example of a base FoodProcessor
> class:
> class FoodProcessor:
>     "Model for a kitchen appliance food processor"
>     speed_settings     # example [1, 2, 3, 4]
>     blade_settings      # example ["slice", "grate", "grind"]
>     slice_thickness     # example ["thin", "thick"], but only if
> blade_setting is "slice"
> it only make sense to have the slice_thickness property set when
> blade_settings = "slice"; otherwise, it would be preferable to only define
> the speed_settings and blade_settings properties.  For example:
> class ProcessorA(FoodProcessor):
>     "A slicing-only processor"
>     speed_settings = [1, 2, 3, 4]
>     blade_settings = "slice"
>     slice_thickness = ["thin", "thick"]
> class ProcessorB(FoodProcessor):
>     "A non-slicing processor"
>     speed_settings = [1,2,3,4]
>     blade_settings = ["grate", "grind"]
>     slice_thickness = None
> Can anyone suggest some work-arounds, or refactoring for this type of
> design?  Is there a design pattern for this?

I'm not sure what the problem is. You can provide default values in
the base class:
class FoodProcessor(object):
  speed_settings = None
  blade_settings = None
  slice_thickness = None

Then in a derived class you can override just the ones you want to use:
class ProcessorB(FoodProcessor):
    "A non-slicing processor"
    speed_settings = [1,2,3,4]
    blade_settings = ["grate", "grind"]

If you want to validate that the current settings make sense, you
could put a test in the __init__() method, which is simple to
implement but happens at instance creation time, or you could write a
metaclass to validate the settings at class creation time, which is
more difficult (to understand, anyway).

Kent


More information about the Tutor mailing list