[Tutor] When to use classes

Steven D'Aprano steve at pearwood.info
Sat Aug 19 21:08:35 EDT 2017


On Sat, Aug 19, 2017 at 11:00:51AM -0500, boB Stepp wrote:

> I try to keep this in mind.  Another thing I'm currently struggling
> with is when to use inheritance vs. separate, independent classes.

Raymond Hettinger has a good video presentation about the use of classes 
and inheritance for delegating work. (That is not to be confused with 
delegation as an alternative to inheritance.)

I think this is the video, but I don't have time to check:

The Art of Subclassing

http://www.youtube.com/watch?v=miGolgp9xq8

If its the one which starts off with him talking about his newly born 
child, it is the one.

And if not, it is probably worth watching anyway, because Raymond's 
talks are always excellent value.

The traditional viewpoint of inheritance is that it is used for 
specialisation, where each subclass is a kind of the parent class:

class Animal:
    # all generic code for animals goes here

class Mammal(Animal):
    # mammals are a kind of animal
    # specialise the animal code for mammals

class Dog(Mammal):
    # dogs are a kind of mammal
    # specialise the mammal code for dogs

class Collie(Dog):
    # collies are a kind of dog
    # specialise the dog code for the collie breed

lassie = Collie()

If you ever hear people talking about the Liskov Substitution Principle, 
that's the model they have in mind. But it's not the only one possible.

Raymond talks about inheritance as expressing a parent-child 
relationship, where the child can delegate tasks to the parent, but the 
child doesn't necessarily need to be seen as "a kind of" whatever the 
parent is.

That's the model used by mixin classes (or traits, a variation on 
mixins).


-- 
Steve


More information about the Tutor mailing list