Doritos
Doritos

Reputation: 423

Python create object depending on a variable name

I am trying to create a Fruit object but I don't know exactly which fruit to create.

I have a dictionary that loaded all the classes into a dictionary.

fruits = {'Apple': <module 'Apple' from '.'>, 'Orange': <module 'Orange' from '.', 'Banana': <module 'Banana' from '.'>

I then have a variable that contains the fruit name I want to create. So I can set this to Apple, Orange, or Banana.

myfruit = 'Orange'

I also have some simple classes.

class Apple:
    def __init__(self):
        pass

class Orange:
    def __init__(self):
        pass

class Banana:
    def __init__(self):
        pass

I want to basically create a object based on whatever myfruit variable is set to.

fruit_obj = myfruit()

My end game is to be able to create a large amount of classes for various things, and then whenever myfruit is set, it creates a object of that type.

EDIT: This is what I am doing to load the key (filename) to module.

def load_up(path):
    COMMAND_FOLDER = path + '/'
    commands = [f for f in listdir(COMMAND_FOLDER) if isfile(join(COMMAND_FOLDER, f)) and f[-3:] == '.py']
    commands_map = {}
    for command in commands:
        name = command[:-3]
        path = COMMAND_FOLDER + command
        spec = spec_from_file_location(name, path)
        foo = module_from_spec(spec)
        spec.loader.exec_module(foo)

        commands_map[name] = foo

    return commands_map

Upvotes: 3

Views: 5453

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36732

Following the import of the various classs, you could do like this, with a dictionary to map the fruit_name to the class to be created

from module import Orange, Apple, Banana


fruits = {'Apple': Apple, 'Orange': Orange, 'Banana': Banana}

myfruit = 'Orange'
fruit_obj = fruits[myfruit]()   # -> creates an object of type Orange

With the following classes in module.py:

class Apple:
    def __init__(self):
        pass

class Orange:
    def __init__(self):
        pass

class Banana:
    def __init__(self):
        pass

Upvotes: 7

Related Questions