Thinking about Python's inheritance model

June 8, 2008

I recently read an entry by someone who was surprised that Python subclasses did not automatically call their parent class's 'constructor' method, by which he meant __init__. This is a straightforward consequence of Python's inheritance model, but Python's inheritance model is slightly odd.

The straightforward way to explain Python's inheritance model is that it uses what I could call 'lookup based' or 'name based' subclassing, where what subclassing does is change what binding will be returned when you look up a given name on an instance of the (sub)class. And that's pretty much it as for what subclassing does.

(Technically subclassing has some additional effects when you use __slots__, but that's another discussion.)

The next thing to know is that all of Python's special operations, including __init__, work by normal method calls; they look up the binding for the name of the special method and then call what they get back (if anything). So in this model it makes perfect sense that there is no upcall to the parent class's __init__ method; your subclass overrode the binding of the name, so your method function gets called instead of the parent's. Doing an upcall would make __init__ a magic special operation, unlike all of the others.

(Note that multiple inheritance does not preclude magic upcalls, since there is a defined method resolution order that the upcalling could follow.)

One consequence of this simple model of subclassing is that you can fake subclassed instances by using other methods and outside people generally won't notice anything. (They can tell if they use isinstance() or the like, but most code shouldn't.)

Written on 08 June 2008.
« Recovering my Eee PC from a post-update problem
Mirrored system disks should be trivial to set up »

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

Last modified: Sun Jun 8 23:51:29 2008
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.