mart1n mart1n - 1 month ago 5
Python Question

Abstracting a class with inheritance

I'm still trying to wrap my head around class inheritance in Python so bear with me: if I have two very similar classes:

class Red:
def print_color(self):
print('red')

class Blue:
def print_color(self):
print('blue')


What's the proper way to inherit these classes to create an abstract class (let's say
Color
) that gets initialized with some sort of an argument that determines which underlying class gets used? After initializing, I should be able to do this:

>>> a = Color('red')
>>> a.print_color()
red

Answer

To make that desired example work exactly as is, this is all you need:

class Color:
    def __init__(self, color):
        self.color = color

    def print_color(self):
        print(self.color)

No inheritance, nothing.

If you actually want Color('red') to result in an instance of the class Red, then Color just needs to be a factory function:

def Color(color):
    constructors = {'red': Red, 'blue': Blue}
    return constructors[color]()

Still no inheritance involved here.

Comments