More thinking about Python's inheritance model

June 23, 2008

Here's something I've been pondering lately: why doesn't Python have an inheritance model more like C++, where (for example) your superclass's __init__ is automatically called?

There's a number of reasons, but I think that one of them is that Python lacks any concept of private class attributes and methods. When you limit what a subclass can do to a superclass, when you have private internal state that has to be maintained correctly, it's clear that you cannot let a subclass block the correct initialization (or destruction) of a parent class. So you have to call the superclass's initializer, and in fact you have to call them from the top of the inheritance tree on down, because you need to prevent the subclass from getting control before the superclass is ready for it.

(To develop this argument slightly more: it doesn't do any good to protect an instance attribute or a class method if you don't also protect the thing's dependencies, and one of the core dependencies is a correctly initialized object. Or in short: protecting the value of an instance attribute is pointless if you don't also protect the fact that it has a defined value.)

Since Python gives classes no such protection it is free to adopt a simpler model of class inheritance, because it is not giving subclasses any power that they don't already have. (And you can argue that the simpler model is also more powerful, since it allows Python subclasses to do things that would probably be impossible in C++.)

(Disclaimer: the author doesn't actually know C++, although he keeps intending to learn it.)

Written on 23 June 2008.
« The implicit versus the explicit
Why I am not really fond of docstrings in Python »

Page tools: View Source, Add Comment.
Search:
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Mon Jun 23 00:17:05 2008
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.