mart1n
mart1n

Reputation: 6233

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

Upvotes: 1

Views: 77

Answers (2)

deceze
deceze

Reputation: 522636

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.

Upvotes: 4

bravosierra99
bravosierra99

Reputation: 1371

So there are a lot of possible answers, but I think a very good one is called the Factory Design Pattern. It's covered in a lot of different places, but here is one that looks decent.

http://python-3-patterns-idioms-test.readthedocs.io/en/latest/Factory.html

Upvotes: 1

Related Questions