[Tutor] Overriding a method in a class
Terry Carroll
carroll at tjc.com
Sat May 14 05:14:30 CEST 2011
On Fri, 13 May 2011, Terry Carroll wrote:
> For my specific case, I'm going to go with a Plan B of using callbacks; and
> provide default unbound callbacks present in the module, but not defined in
> the class itself.
Here's a callback-with-default approach, which works:
### Thing.py ############
def add_the_stuff(obj, s1):
obj.stuff.append(s1)
class Thing(object):
def __init__(self, callback=add_the_stuff):
self.stuff = []
self.cb=callback
def addstuff(self, text):
self.cb(self, text)
#########################
##### toy2.py ###########
import Thing
A = Thing.Thing()
A.addstuff("ABCDEFG")
print A.stuff
def addlower(obj, s2):
obj.stuff.append(s2.lower())
B = Thing.Thing(callback=addlower)
B.addstuff("WXYZ")
print B.stuff
########################
Which produces, as expected:
>toy2.py
['ABCDEFG']
['wxyz']
But still...
> But I'd still like to have a better understanding of how the call gets
> transmuted from a two-argument call to a one-argument call based upon the
> target.
More information about the Tutor
mailing list