John M. Gabriele a écrit :
> Consider the following:
> 
> #!/usr/bin/python
> 
> #-----------------------------------------------------------------
> class Grand_parent( object ):
> 
>     def speak( self ):
>         print 'Grand_parent.speak()'
>         self.advise()
> 
>     def advise( self ):
>         print 'Grand_parent.advise()'
>         self.critique()
> 
>     def critique( self ):
>         print 'Grand_parent.critique()'
> 
> 
> #-----------------------------------------------------------------
> 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()'
> 
> 
> #-----------------------------------------------------------------
> print 'speak() calls advise(), then advise() calls critique().'
> print
> 
> people = [ Grand_parent(), Parent(), Child() ]
> for person in people:
>     person.speak()
>     print
> 
> 
> 
> ====================
> The output is:
> 
> speak() calls advise(), then advise() calls critique().
> 
> Grand_parent.speak()
> Grand_parent.advise()
> Grand_parent.critique()
> 
>         Parent.speak()
>         Parent.advise()
> Grand_parent.critique()
> 
>                 Child.speak()
>         Parent.advise()
>                 Child.critique()
> 
> 
> What's going on here with that last "Child.critique()"? The
> Parent called self.critique(), and since it *had* no critique()
> method, it should've deferred to it's parent's critique()
> method, right? But instead, somehow Child.critique() got called.
> Why?
> 
> ---J
> 
Because that's the way virtual methods are supposed to work. When you 
can a methon foo on an object, you always start your search from the 
current object class and not the class of the current function.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to