Replacing base class
DH
no at sp.am
Wed Mar 3 10:54:12 EST 2004
Alexey Klimkin wrote:
> Hello!
>
> Is it possible in python to replace base class with another one?
>
> Assume an example:
> class A:
> def f(self):
> print 'A'
> class B(A):
> def f(self):
> A.f(self)
> print 'B'
> class C:
> def f(self):
> print 'C'
>
> I need to make class Bm with the same functionality as B, but
> derived from C, instead of A. Classes C and A have the same
> interface.
>
> The call of f() for Bm should output:
> C
> B
>
> As you see, the main problem is B.f, since it uses f() from base
> class. Any clues?
>
You might want to give some more details about what you are really
doing, because there are multiple ways to do this, but the simplest is
to just replace A.f(self) with:
super(B,self).f(self)
And make your classes subclass "object" so they are new style classes
(required for "super" to work).
Another option is to make "B" a mixin class that can work with A or C or
both:
class B: #mixin
def f(self):
for base in self.__class__.__bases__:
if (base is not B) and hasattr(base,"f"):
base.f(self)
print 'B'
class Test(B,C,A): pass #put mixin class first
But you might also want to create an "interface" class that specifies
the "f" method, which A & C "implement".
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/164901
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204349
http://peak.telecommunity.com/PyProtocols.html
Then in B, you could call f() on all bases that implement that interface
if you liked.
More information about the Python-list
mailing list