0

I have a class structure like

class A:
    def method1(self):
        return 1

class B:
    def method2(self):
        return 2

class C(A,B):
    def method3(self):
        return self.method1()+self.method2()

The Classes A and B provide functionality which class C gathers and enriches with some wrappers. Now it happens that I need a similar class C2 which is derived from a different implementation A2 instead of A: class C2(A2, B) with the same method3.

How would you realize such a design (C can derive from different implementation classes)?

If it has to do with advanced Python programming (meta-classes?) an example would be appreciated :)

2
  • It's not clear what you're asking. If you need another class that inherits from a different base class, just define your new class so it inherits from that base class. Commented Jun 20, 2012 at 19:31
  • I don't want to copy and paste the code of method3. Commented Jun 20, 2012 at 19:32

1 Answer 1

4
class CMixin:
    def method3(self):
        return self.method1()+self.method2()

class C1(A,B, CMixin):
    pass

class C2(A2,B, CMixin):
    pass

Though the design you describe sounds like you want aggregation instead:

class C:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def method3(self):
        return self.a.method1() + self.b.method2()


c1 = C(a1, b)
c2 = C(a2, b)
Sign up to request clarification or add additional context in comments.

2 Comments

This was my first thought. Simple is better.
Oh. Somehow I wasn't aware that I can use methods that aren't in the base classes yet :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.