A question about Python Classes
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Apr 21 21:53:47 EDT 2011
On Thu, 21 Apr 2011 19:00:08 +0100, MRAB wrote:
>>> How can HomeHandler call foo() when I never created an instance of
>>> BaseHandler?
>>
>> But you created one!
>>
> No, he didn't, he created an instance of HomeHandler.
>
>> test is an instance of HomeHandler, which is a subclass of BaseHandler,
>> so test is also an instance of BaseHandler.
>>
> test isn't really an instance of BaseHandler, it's an instance of
> HomeHandler, which is a subclass of BaseHandler.
Which *also* makes it an instance of BaseHandler. You are a human being,
which also makes you a mammal. It would be *wrong* to say that you're not
a mammal, just because you're a human being.
But to answer the Original Poster's question... you don't need a formal
BaseHandler instance because that's how inheritance is designed to work.
Each class knows its own parent classes, and when you call test.foo(),
Python walks the chain of:
instance
instance's class
each of the parent class(es) (if any)
looking for a match for foo, and then calls it appropriately. This is
called inheritance: HomeHandler inherits behaviour from BaseHandler.
(The details are a little more complex than the sketch above, but broadly
equivalent.)
--
Steven
More information about the Python-list
mailing list