Search code examples
pythoninheritancedynamicmultiple-inheritance

conditional class inheritance in python


I am trying to dynamically create classes in Python and am relatively new to classes and class inheritance. Basically I want my final object to have different types of history depending on different needs. I have a solution but I feel there must be a better way. I dreamed up something like this.

class A:
    def __init__(self):
        self.history={}
    def do_something():
        pass

class B:
    def __init__(self):
        self.history=[]
    def do_something_else():
        pass

class C(A,B):
    def __init__(self, a=False, b=False):
        if a:
            A.__init__(self)
        elif b:
            B.__init__(self)

use1 = C(a=True)
use2 = C(b=True)

Solution

  • I'm assuming that for some reason you can't change A and B, and you need the functionality of both.

    Maybe what you need are two different classes:

    class CAB(A, B): 
        '''uses A's __init__'''
    
    class CBA(B, A):
        '''uses B's __init__'''
    
    use1 = CAB()
    use2 = CBA()
    

    The goal is to dynamically create a class.

    I don't really recommend dynamically creating a class. You can use a function to do this, and you can easily do things like pickle the instances because they're available in the global namespace of the module:

    def make_C(a=False, b=False):
        if a:
            return CAB()
        elif b:
            return CBA()
    

    But if you insist on "dynamically creating the class"

    def make_C(a=False, b=False):
        if a:
            return type('C', (A, B), {})()
        elif b:
            return type('C', (B, A), {})()
    

    And usage either way is:

    use1 = make_C(a=True)
    use2 = make_C(b=True)