1

I have two inherited classes in a module shape.py :

class Shape(object):

class Triangle(Shape):

class Square(Shape):

In my main code I want to instantiate a Shape but I don't know what kind of shape it will be. The shape depends on a user input or a setting.

What would be the best way to get the right instance according to a setting or a user input in Python ?

Jpaille
  • 123
  • 2
  • 6

1 Answers1

0

You can create a dictionary with the expected input as key and the class as value (note that there are no ()):

class_dict = {'triangle': Triangle, 'square': Square}

user_input = input()

shape_object = class_dict[user_input]()

If the user inputs triangle, shape_object will be a Triangle instance, and if the user inputs square then shape_object will be a Square instance.

Note that this is a basic example, and if the user inputs neither 'triangle' nor 'square' then an KeyError will be raised.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Thanks. I found a design here https://github.com/evandempsey/python-design-patterns/blob/master/patterns/factory.py. They use a `ShapeFactory `. I don't really now what is the best option... – Jpaille Sep 29 '16 at 08:44
  • This is pretty much the same, they simply replace the dictionary in my example with a class with `if` statements. I personally prefer the dictionary. Shorter and cleaner. – DeepSpace Sep 29 '16 at 08:46