A question about Python Classes

MRAB python at mrabarnett.plus.com
Thu Apr 21 14:00:08 EDT 2011


On 21/04/2011 18:12, Pascal J. Bourguignon wrote:
> chad<cdalten 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.
If you do this:
 class BaseHandler(object):
 def foo(self):
 print "Hello"
 class HomeHandler(BaseHandler):
 pass
 test = HomeHandler()
then you'll find:
 >>> isinstance(test, BaseHandler)
True
but:
 >>> type(test)
<class '__main__.HomeHandler'>


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /