A question about Python Classes
Ethan Furman
ethan at stoneleaf.us
Fri Apr 22 15:38:21 EDT 2011
Kyle T. Jones wrote:
> Ethan Furman wrote:
>> chad wrote:
>>> 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?
>>
>> You don't need to create an instance of BaseHandler. You have the
>> class, Python knows you have the class -- Python will look there if the
>> subclasses lack an attribute.
>>
>> ~Ethan~
>>
>
> Really? That's not at all how I thought it worked in Python
> (post-instantiation referencing of class and superclass code...)
I'm not sure exactly what you're asking/stating, but does this help?
8<---Py 3.2 code------------------------------------------
class BaseClass():
def bFoo(self):
print("Base foo here!")
class NormalClass(BaseClass):
def nFoo(self):
print("Normal foo here.")
class EnhancedClass(NormalClass):
def eFoo(self):
print("Enhanced foo comin' at ya!")
class EnrichedClass(EnhancedClass):
def rFoo(self):
print("Am I glowing yet?")
test = EnrichedClass()
test.bFoo()
test.nFoo()
test.eFoo()
test.rFoo()
def newFoo(self):
print("Ha! You've been replaced!")
BaseClass.bFoo = newFoo
test.bFoo()
8<----------------------------------------------------------
More information about the Python-list
mailing list