A question about Python Classes
steve+comp.lang.python at pearwood.info
Sat Apr 23 20:03:17 EDT 2011
On Sat, 23 Apr 2011 13:30:02 -0700, chad wrote:
> On Apr 22, 12:47 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
>> On Thursday, April 21, 2011 11:00:08 AM UTC-7, MRAB wrote:
>> > On 21/04/2011 18:12, Pascal J. Bourguignon wrote:
>> > > chad<cda... at gmail.com> writes:
>> > >> Let's say I have the following....
>> > >> class BaseHandler:
>> > >> def foo(self):
>> > >> print "Hello"
>> > >> class HomeHandler(BaseHandler):
>> > >> pass
>> > >> Then I do the following...
>> > >> test = HomeHandler()
>> > >> test.foo()
>> > >> 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.
>> I'm going to vote that this is incorrect usage. An instance of
>> HomeHandler is also an instance of BaseHandler, and it is incorrect to
>> say it is not. The call to HomeHandler does create an instance of
> What do you mean by the "call to HomeHandler"? Don't I call HomeHandler
> after I create an instance of BaseHandler?
The process you do is:
(1) Create the class BaseHandler.
(2) Create the class HomeHandler, which is a subclass of BaseHandler.
(3) Call HomeHandler.
At no point do you create a *direct* instance of BaseHandler (e.g. by
calling BaseHandler). However the instance of HomeHandler is ALSO an
instance of BaseHandler by virtue of the is-subclass relationship:
>>> issubclass(HomeHandler, BaseHandler)
>>> isinstance(test, HomeHandler)
>>> isinstance(test, BaseHandler)
If you *had* created a direct instance of BaseHandler by calling
>>> base = BaseHandler()
>>> isinstance(base, BaseHandler)
>>> isinstance(base, HomeHandler):
It's like this... "Toyota Prius" is a subclass of "Motor Vehicle", so
each and every Prius car is also a motor vehicle. But not every motor
vehicle is a Toyota Prius.
More information about the Python-list