0

I have following piece of code in Python. There are two classes A2 and B2 which share functions f1() and f2(). They differ in their base classes, deriving from A and B respectively.

I can see how to generalize this in C++ using templates. But I am not sure how to do this Python.

class A2(A):   
    def __init__(self):   
        A.__init__(self)   
        self._Z = Z('high')

    def f1(self):   
        return self._Z.f1() 

    def f2(self):   
        return self._Z.f2() 

    # ... more functions ...


class B2(B):   
    def __init__(self):   
        B.__init__(self)   
        self._Z = Z('low')

    def f1(self):   
        return self._Z.f1() 

    def f2(self):   
        return self._Z.f2() 

    # ... more functions ...

1 Answer 1

3

If I understand your question, you might try a mixin class:

class Mixin(object):

    def f1(self):   
        return self._Z.f1() 

    def f2(self):   
        return self._Z.f2() 


class A2(A, Mixin): 

    def __init__(self):   
        A.__init__(self)   
        self._Z = Z('high')


class B2(B, Mixin):   
    def __init__(self):   
        B.__init__(self)   
        self._Z = Z('low')
Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way to avoid Multiple Inheritance?
@Anand have A and B inherit from Mixin. But why?
Python does not have the same problems with multiple inheritance that C++ does.
@LukasGraf Little scared of Multiple inheritance. Can this be solved using metaprogramming methods?
@Anand Yes, it can. For instance, you could use a class decorator to define the common methods. But mixin classes are an establish pattern in Python, and are the simplest solution to your dilemma. Metaprogramming is cool, but simplicity > cool.
|

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.