mart1n mart1n - 9 months ago 48
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):

class Blue:
def print_color(self):

What's the proper way to inherit these classes to create an abstract class (let's say
) 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()

Answer Source

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):

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.