Extending Methods Vs Delegates

vbgunz vbgunz at gmail.com
Tue Mar 21 18:57:11 EST 2006


Hello everyone.

I own two books. Learning Python and Python in a nutshell. When cross
referencing the two books to try and clarify the ideas behind extending
methods and delegates, this is where confusion veered it's ugly head :(

Learning Python explains on page 324: Class Interface Techniques
(21.3.3 in the ebook) the following is an extender method.

''' #################################### '''

class SuperClass:
  def method(self):
    print 'SuperClass.method'

class SubClass(SuperClass):
  def method(self):
    print 'SubClass.method'
    SuperClass.method(self)

x = SubClass()
x.method()

''' #################################### '''

the purpose of the above is so SubClass does not completely override
the SuperClass method. This makes sense and is very easy to follow.
Here is where things get a bit hazy... Learning Python also explains
that the following is what is called a delegate (same page in book).

''' #################################### '''

class SuperClass:
  def delegateMethod(self):
    self.action()

class SubClass(SuperClass):
  def action(self):
    print 'SubClass.action()'

x = SubClass()
x.delegateMethod()  # calls SubClass.action()

''' #################################### '''

I went back and fourth in the Learning Python book for a clearer
explanation on what exactly is a delegate and came up empty. Here is
where the confusion was unleashed in all it's fury. When I decided to
cross reference the idea of delegates with Python in a nutshell, it
said example one above is the delegate...

What?

Python in a nutshell explains on page 80: Delegating to superclass
method (5.1.6.2 in the ebook) that the first example above (extending
to Learning Python) is the actual delegate. You're probably confused
too huh? I'll try to explain.

Learning Python touches on extending and delegating methods. Extending
them in Learning Python seems to make perfect sense. Learning Python
didn't do a great job on really explaining what a delegates purpose and
application is *so* when I decided to cross reference it with Python in
a nutshell, Python in a nutshell explains that extending (according to
LP) is really delegating...

I hope I've made some sense with this question. I ultimately wish to
know just one real thing. Regardless of the name of the second example
above, what is the purpose of calling a sub class method from a super
class instance? What is the application to such a design? The reason I
ask is because it is honest to god confusing and I've heard of
delegates before...

Maybe an example will help?

I could be off entirely... One of the books have to be wrong or like my
wife mentioned, maybe they both touch on half the truth? Any help is
greatly appreciated!




More information about the Python-list mailing list