3

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
3
  • 1
    Map it differently: {'Apple': Apple, 'Orange': Orange} Commented Jul 15, 2019 at 16:35
  • 1
    Does fruit_obj = fruits[myfruit]() work for you? Commented Jul 15, 2019 at 16:46
  • @OlivierMelançon I get TypeError: 'module' object is not callable. Commented Jul 15, 2019 at 16:47

1 Answer 1

7

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.