code review

Steven D'Aprano steve+comp.lang.python at
Sat Jun 30 04:28:52 CEST 2012

On Fri, 29 Jun 2012 19:41:11 +0000, Alister wrote:

> also this section in main strikes me as a bit odd and convoluted
>     w = world()
>     serv = server(client)
>     w.server = serv
> = w
> I think you are cross referencing classes & would be better to
> investigate inheritance.

What you show above is composition, and is a perfectly valid technique, 
and in fact should often be *preferred* to inheritance.

The only slightly dubious part, and I stress *slightly*, is that there is 
a circular reference: w refers to serv, and serv refers back to w. While 
legitimate, it is a very slight "code smell" that should be investigated. 
If there is a way to get the same result without the circular reference, 
that would be preferred.

For example, perhaps server methods that need to know the world could 
take it as an explicit argument, rather than fetching it implicitly from

Or, a moderately advanced technique, use a weak-ref instead.

Inheritance should only be used to model "is-a" relationships. For 
example, Herbie the Love Bug is a Volkswagen Beetle, so inheritance is 

class Vehicle(object):

class Car(Vehicle):

class Beetle(Car):

herbie = Beetle()

Composition should be used to model "has-a" relationships. For example, a 
car has an engine, it is not a kind of engine, and so inheritance is 
inappropriate and composition should be used. I would re-write the Car 
class as follows:

class Engine(object):

class Car(Vehicle):
    def __init__(self):
        self.engine = Engine()

So now we can talk about Herbie's engine:

herbie.engine  # Herbie, being a car, has an engine, he is not an engine


More information about the Python-list mailing list