OOP: method overriding works in mysterious ways?

André andre.roberge at gmail.com
Mon Jan 2 15:44:19 EST 2006


John M. Gabriele wrote:
> Consider the following:
>
[snip]

> #-----------------------------------------------------------------
> class Parent( Grand_parent ):
>
>      def speak( self ):
>          print '\tParent.speak()'
>          self.advise()
>
>      def advise( self ):
>          print '\tParent.advise()'
>          self.critique()
>
>      # ATM, the Parent is at a loss for words, and has no critique.
>
>
> #-----------------------------------------------------------------
> class Child( Parent ):
>
>      def speak( self ):
>          print '\t\tChild.speak()'
>          self.advise()
>
>      # Currently, the Child has no really useful advice to give.
>
>      def critique( self ):
>          print '\t\tChild.critique()'
>
>

Since Child has no advice() method, it inherits the one for Parent.
Thus, Child can be thought of as being defined as follows:

. class Child( Parent ):
.
.      def speak( self ):
.          print '\t\tChild.speak()'
.          self.advise()
.
.      def advise( self ):   # inherited from Parent
.          print '\tParent.advise()'
.          self.critique()
.
.      def critique( self ):
.          print '\t\tChild.critique()'
.
Note that "self" refer to the *instance* created, not the *class*.

> print 'speak() calls advise(), then advise() calls critique().'
> print
>
> people = [ Grand_parent(), Parent(), Child() ]
> for person in people:
>      person.speak()               ### calls the instance's relevant method
>      print

[snip]
>
>                  Child.speak()
>          Parent.advise()               #inherited from Parent
>                  Child.critique()
> 
> 

Now, does the output make sense?

André




More information about the Python-list mailing list