0
class classA:
    def common(self):
        print('A')

class classB:
    def common(self):
        print('B')

class classC:
    def workflow(self):
        print('Do something')
        self.common()
        print('Do something else')


A = classC() # Here I want to create classC that inherits from classA
A.workflow()
assert isinstance(A, classA)

B = classC() # Here I want to create classC that inherits from classB
B.workflow()
assert isinstance(B, classB)

In this example I have classA and classB that both implement a function common() that outputs a different value. I'd like to have classC inherit from one of those classes such that workflow() will have a slightly different behavior depending on which common() method it inherits. The main goal of this is to have one workflow() method where the result of self.common() changes depending on the inheritance.

How can I choose which class classC inherits from when I instantiate classC?

Takkun
  • 6,131
  • 16
  • 52
  • 69

1 Answers1

0

You can't pick a different parent class for individual objects; classes handle inheritance. That said, you can create a new class on demand by using type directly. You won't be using classC directly, but a child class that inherits from both classC and the appropriate one of classA and classB, treating the two as mix-in classes.

a = type("pick-a-name", (classC, classA), {})()
b = type("pick-a-name", (classC, classB), {})()

You'll note there's an extra expense here, in that every time you try to instantiate an object, you have to create a new class first. You might as well define the child classes right away.

class Ca(classC, classA):
    pass

class Cb(classC, classB):
    pass
chepner
  • 497,756
  • 71
  • 530
  • 681