Q? Calling nearest inherited method
Thomas Wouters
thomas at xs4all.net
Wed May 17 08:51:10 EDT 2000
On Wed, May 17, 2000 at 11:54:53AM +0000, Oleg Broytmann wrote:
> On Wed, 17 May 2000, Laurent POINTAL wrote:
> > Given a class hierarchy like this:
> > A
> > B inherits A
> > C inherits B
> >
> > A define dothis method.
> > C define dothis method.
> >
> > In the C.dothis, I wants to call my nearest parent class dothis
> > method. That is, call B.dothis if it is defined, or A.dothis if it is
> > defined...
> I think B.dothis() will do it just right, no?
Yes, but dont forget to manually pass 'self' (or whatever you call the first
argument in your method.)
class C(B):
def dothis(self, x):
# your code here
B.dothis(self, x)
# more code here
If you aren't sure if B has a 'dothis' method (either from itself or
inherited) wrap the call in a try/except. And if you dont want to hard-code
the name of the parent class in more than one place (the class line), use
self.__class__.__bases__. This is a tuple containing the base classes for
that class. If you want to call all possible dothis() methods, in all
parents, you could do something like this:
def dothis(self, *args, **kwargs):
for parent in self.__class__.__bases__:
try:
method = parent.dothis
except AttributeError:
continue
apply(method, (self,)+args, kwargs)
or if you just want to call the first one you find, either change the last
line to 'return apply ...' or add a 'break' after the 'apply'.
--
Thomas Wouters <thomas at xs4all.net>
Hi! I'm a .signature virus! copy me into your .signature file to help me spread!
More information about the Python-list
mailing list