super() and automatic method combination
Laszlo Zsolt Nagy
gandalf at geochemsource.com
Wed May 18 09:18:01 EDT 2005
>
>I have the impression that this is supposed to call the f method
>in both A and B, so it should print
>
>
Not really true. The first parameter of 'super' should be a type, not an
instance.
> A
> B
> C
>or maybe
> B
> A
> C
>depending on the resolution order. However, it only calls A.f and not B.f.
>
>I also notice that if I say
>
>
> class B(object):
> def f(self):
> super(B,self).f()
> print 'b'
>
>then
> test(B)
>raises an exception since B has no superclass with an f method.
>
Correct. When you use super(B,self) it accesses the current instance as
the class B. If it has no method named 'f' then this will end up in an
exception.
>That doesn't seem like such a good thing necessarily.
>
>
But yes, it is. When you try to call a nonexistent method, it should
raise an exception.
>Anyway, is there a preferred way of writing this example so that C.f
>automatically calls both A.f and B.f?
>
>
I do not know a preferred way. However, I made this example for you, I
hope it helps.
class CallSupersMixin(object):
def callsupers(self,fname,*args,**kwargs):
l = self.__class__.__bases__
for cls in l:
if hasattr(cls,fname):
getattr(cls,fname)(self,*args,**kwargs)
elif cls == CallSupersMixin:
pass
else:
raise AttributeError("Base class %s does not have a
method named %s " % ( str(cls),fname ) )
class A(object):
def f(self):
print 'A.f called'
class B(object):
def f(self):
print 'B.f called'
class AB(A,B,CallSupersMixin):
def f(self,*args,**kwargs):
self.callsupers('f',*args,**kwargs)
ab = AB()
ab.f()
Of course you can remove the "raise AttributeError" part. Then it will
call only the classes that have the given method.
I know it is not a very good example but you can go from here.
Best,
Laci 2.0
--
_________________________________________________________________
Laszlo Nagy web: http://designasign.biz
IT Consultant mail: gandalf at geochemsource.com
Python forever!
More information about the Python-list
mailing list