On 8 April 2013 10:44, Antoon Pardon <antoon.par...@rece.vub.ac.be> wrote: > Here is the idea. I have a number of classes with the same interface. > Something like the following: > > class Foo1: > def bar(self, ...): > work > def boo(self, ...): > do something > self.bar(...) > > What I want is the equivallent of: > > class Far1(Foo1): > def boo(self, ...) > do something different > if whatever: > self.bar(...) > else: > Foo1.boo(self, ...) > > Now of course I could subclass every class from the original family > from Foo1 to Foon but that would mean a lot of duplicated code. Is > there a way to reduce the use of duplicated code in such circumstances? >
(Python 3) ------------------------------ class Foo1: def bar(self): print('Foo1.bar') def boo(self, whatever): print('Foo1.boo', whatever) self.bar() # class Foo2: ...(I'll let you define this one) class DifferentBoo: def boo(self, whatever): print('DifferentBoo.boo', whatever) if whatever: self.bar() else: super().boo(whatever) class Far1(DifferentBoo, Foo1): pass # class Far2(DifferentBoo, Foo2): pass ------------------------------ >>> foo = Foo1() >>> foo.bar() Foo1.bar >>> foo.boo(1) Foo1.boo 1 Foo1.bar >>> far = Far1() >>> far.bar() Foo1.bar >>> far.boo(0) DifferentBoo.boo 0 Foo1.boo 0 Foo1.bar >>> far.boo(1) DifferentBoo.boo 1 Foo1.bar HTH, -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list