Python Design Patterns - composition vs. inheritance

Neil Cerutti horpner at yahoo.com
Fri Nov 16 12:02:22 EST 2007


On 2007-11-16, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:
> On Thu, 15 Nov 2007 12:28:28 -0800 (PST), "snewman18 at gmail.com"
><snewman18 at gmail.com> declaimed the following in comp.lang.python:
>
>> 
>> As a very simplified example, if I had two classes, Pet and Owner, it
>> seems that I would not have Pet inherit from Owner, since a pet 'has
>> an' owner, but not 'is an' owner. If this is correct, does my code
>> below reflect this? I passed the owner object into the pet object's
>> constructor - is this the right way to do it?
>>
> 	Well, other than the facet that I'd say "Owner" has-a "Pet", but
> this example is a bit too disjoint for the association (IE, it goes both
> ways)
>
> 	A common example is something like:
>
> class Vehicle(object):
> 	#which has attributes for speed, direction, cargo capacity,
> passenger capacity
>
> class RoadVehicle(Vehicle):
> 	#inherits (RoadVehicle IS-A Vehicle with Axles)
>
> class Auto(RoadVehicle)
> 	#  HAS-A Front-Axle, Rear-Axle
> 	#	and Axle HAS-A Left-Tire, Right-Tire (unless a Dual -- with
> inner left, outer left, inner right, outer right, those those would
> appear on Bus(RoadVehicle) and Truck(RoadVehicle) classes)
>
> Look up "Law of Demeter" (I believe that is the name). The idea
> is that a "user" of, say, Auto, should NOT need to know that it
> has tires (may know it has axles, so it may have a
> "listAxles()" method, which returns a list/tuple of the axles
> that the Auto has. You could then use that list to access the
> tires on each axle { for tire in aRoadVehicle.listAxles():
> print tire.specification() }

The Law of Demeter constrains the attributes that the methods of
Auto may invoke. Given the above containment hierarchy, the Law
says that no method of Auto may depend on any attribute or method
of Tire. So if you needed to compute, in an Auto method,
something that depends on an attribute of Tire, you must make
that information available directly through the Axle interface.

The benefit is that this lowers the coupling between classes. The
Tire interface can change completely without affecting the Auto
class.

> BUT... Just look at the Python library... sys.stdout.write(),
> if following Law of Demeter would turn into:
>
> 	myStdout = sys.getStdout()
> 	myStdout.write()

The Law of Demeter doesn't apply to that example.

-- 
Neil Cerutti



More information about the Python-list mailing list