A question about Python Classes
Jean-Michel Pichavant
jeanmichel at sequans.com
Fri Apr 22 05:47:18 EDT 2011
MRAB wrote:
> 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.
I think this is really wrong within the OP question context. This is a
key concept about OOP and inheritance, any object of class HomeHandler
is an object of class BaseHandler and also an object of any other base
class.
However it is true that for convenience, there are some language abuses
around this terms that we're all using, for instance:
- class refers to the lowest class of the object (like the python
__class__ attribute)
- "instance of" means sometimes "created using the constructor of"
when stating for example that you cannot create an instance of a
virtual class. From a formal OO POV, anyone can create an instance of a
virtual class, you just need to create an instance of one of its
subclass. What you cannot, is create a instance of a virtual class using
the constructor of that virtual class.
Also note that
isinstance(test, BaseHandler)
returns True. And this is no Python trick to trigger some magic, this is
what OO is about.
JM
More information about the Python-list
mailing list