473,326 Members | 2,136 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Extending Methods Vs Delegates

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!

Mar 22 '06 #1
5 3807
vbgunz <vb****@gmail.com> wrote:
...
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
I'm not using "delegate" in any specialized technical sense, e.g.
(picking from a google search on [define:delegate]), "person designated
to act for or represent another or others". Here, object, not person,
of course. What the Learning book chooses to call ``delegate'' is
commonly known in the programming world by the (lousy) name "Template
Method design pattern" (I like to call it "self-delegation", but that's
just me).

I regret Ascher and Lutz's choice to muddy the waters by implying that
"delegate" has this very specialized meaning...
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...


Forget the naming: the purpose of the Template Method design pattern is
to abstract the structure in the superclass while allowing subclasses to
see to the details. A great pattern (w/a lousy name). Several of my
presentations (you can find them in the english-language half of
www.aleax.it) touch on design patterns in Python. I guess I'll have to
write a real essay about that sooner or later -- meanwhile, try to make
do with my presentations, my posts
<http://groups.google.com/groups?as_q...=en&as_epq=tem
plate+method&as_oq=&as_eq=&as_ugroup=&as_usubject= &as_uauthors=alex+mart
elli&lr=&as_drrb=q&as_qdr=&as_mind=1&as_minm=1&as_ miny=1981&as_maxd=21&a
s_maxm=3&as_maxy=2006&safe=off>, and what you can find by google search
on ["template method" design pattern]...
Alex
Mar 22 '06 #2
I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my
bible and I take it virtually everywhere! Seriously, I would highly
recommend it to anyone with a little to a lot of Python experience.

I apologize for misinterpreting your passage on page 80. I will look
much closer at your examples, links and ideas and I hope to straighten
my knowledge on the subject of delegates!

Thank you for hinting on the "Template Method design pattern"! Sorry
for any misunderstanding!

Mar 26 '06 #3
vbgunz enlightened us with:
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?
I've seen this style of programming before, in wxWidgets. The
constructor of a class does various things. This is roughly what
happens:

class wxSomeClass(wxParent):
def __init__(self, *args, **kwargs):
# Do various things

if not self.OnInit():
raise RuntimeError("Initialization failed")

# Do other things that need to be done after custom
# initialization

def OnInit(self):
return True

This makes it easier to simply provide custom initialization, without
having to redo everything in __init__. Calling the superclass'
function is fine if you want to add behaviour before and/or after
calling it. This example however lets you customize behaviour that's
put in the middle of the __init__ function.
Maybe an example will help?


I hope so :)

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Mar 26 '06 #4
vbgunz <vb****@gmail.com> wrote:
I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my
bible and I take it virtually everywhere! Seriously, I would highly
recommend it to anyone with a little to a lot of Python experience.

I apologize for misinterpreting your passage on page 80. I will look
much closer at your examples, links and ideas and I hope to straighten
my knowledge on the subject of delegates!

Thank you for hinting on the "Template Method design pattern"! Sorry
for any misunderstanding!


Hey, no problem -- such a misunderstanding is always a shared
responsibility, and as an author I need to take my part of the blame.

Unfortunately, the root issue is that more and more common, ordinary,
useful English words get expropriated by specialized technical meanings,
making it almost impossible to discuss technical matters in ordinary
English without *some* risk of misunderstanding (by the reader
mistakenly seeing a "specialized, technical meaning" where the NORMAL
English use of the word, possibly in a slightly metaphorical vein, is
what the author meant). From "function" and "procedure", to "delegate"
and "built-in", a growing number of words become "risky"!-)

Funny enough, the problem is worst in English - because in many other
languages, the specialized technical terms often use borrowed English
words, so the other language's native terms remain available. Latin had
similar luck wrt Greek a couple millennia ago -- all technical terms of
philosophy were borrowed Greek words, so the risk of confusion was in
fact much lower than it was in Greek;-).
Alex
Mar 26 '06 #5
On Sun, 2006-03-26 at 07:21 -0800, Alex Martelli wrote:
vbgunz <vb****@gmail.com> wrote:
I am sorry I couldn't reply sooner! Alex, Python in a nutshell is my
bible and I take it virtually everywhere! Seriously, I would highly
recommend it to anyone with a little to a lot of Python experience.

I apologize for misinterpreting your passage on page 80. I will look
much closer at your examples, links and ideas and I hope to straighten
my knowledge on the subject of delegates!

Thank you for hinting on the "Template Method design pattern"! Sorry
for any misunderstanding!


Hey, no problem -- such a misunderstanding is always a shared
responsibility, and as an author I need to take my part of the blame.

Unfortunately, the root issue is that more and more common, ordinary,
useful English words get expropriated by specialized technical meanings,
making it almost impossible to discuss technical matters in ordinary
English without *some* risk of misunderstanding (by the reader
mistakenly seeing a "specialized, technical meaning" where the NORMAL
English use of the word, possibly in a slightly metaphorical vein, is
what the author meant). From "function" and "procedure", to "delegate"
and "built-in", a growing number of words become "risky"!-)

Funny enough, the problem is worst in English - because in many other
languages, the specialized technical terms often use borrowed English
words, so the other language's native terms remain available. Latin had
similar luck wrt Greek a couple millennia ago -- all technical terms of
philosophy were borrowed Greek words, so the risk of confusion was in
fact much lower than it was in Greek;-).


Of course, any language suffers that problem when the rise of a new
field is associated with it.

Medicine draws from Latin. For English speakers that is wonderful, a
whole language from which to assign specific meanings. But consider Mr.
DaVinci at one of his past-times, the dissection of rapidly decomposing
corpses for the secrets hidden within. That he might choose to spell
his description of the inside of an eye as vitreous humor, instead of
say, eye slime, didn't make it sound as impressive to him as the term
does to me today. I almost feel that a true appreciation for the
complexity of any endeavor must wait until its native language passed a
bit from the spot light.

While I can't speak for other fields, I believe that our "linguistic
address space" does limit our progress. Take list interpolations for
instance ... interpolation has other, specific meanings in other not so
far removed fields. When I first read about it, I had to backup and
think for a moment, if only to resolve the fact that yet another term is
overloaded.

And even our keyboards limit our space. I can create a tuple (), or a
list [], or a dict{}, but why can't I create another structure .. oh
wait, we are out of parenthesis like characters, and nobody has the
courage to recycle the of HTML fame <> pair.

Now, as I work on my mutable sequences PEP and implementation, I find
myself annoyed without a good, non-overloaded, way of naming an iter
friendly variant of a data store's normal __delitem__. Actually, this
wasn't more than a minute long problem, but the rate of collisions
within the English word space is a problem. At least English is pretty
friendly about adopted and synthetic words.

Cheers - Adam

Mar 26 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Carl Youngblood | last post by:
I imagine this subject has probably been brought up numerous times. Forgive me for bringing it up again. I was googling through old posts on this newsgroup about it and found a good suggestion on...
8
by: Michael McDowell | last post by:
I'm confused: "why do we need to assign a method to a delegate then assign the delegate to an event why not just assign the method to the events event handler" and "how does making a...
175
by: Ken Brady | last post by:
I'm on a team building some class libraries to be used by many other projects. Some members of our team insist that "All public methods should be virtual" just in case "anything needs to be...
4
by: theBoringCoder | last post by:
Hello All, I just started learning about Delegates, and was wondering if someone could point me at some useful, straightforward examples of how to use delegates to make method calls...
4
by: Einar Høst | last post by:
Hi, I'm using delegates to show progress when performing certain tasks. However, I'd like to check to see that there actually is a method available for the delegate to call. What's the correct...
5
by: Rene | last post by:
I created a class (SomeClass), on that class, I declared a delegate (OnXyz) and then declared an event based on that delegate (Xyz). All this in the same class. After that, I created another class...
3
by: | last post by:
I am enjoying making generalized methods to serve common needs, such as: ImageProcessing.MakeQuickResize(); ImageProcessing.Sharpen(); FileOps.CreateYearAndMonthAndDayDirectoryBasedOnDate()...
4
by: Frankie | last post by:
I have just gotten up to speed on what anonymous methods are (syntax, capabilities, etc), and how they can be used with /called via delegates. What I am wondering is... 1. Are they only/mostly...
5
by: puzzlecracker | last post by:
thanks
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.