1

Let's say we have a few different classes: ClassA, ClassB, ClassC, and ClassD. I have a variable I will set based on different circumstances. I know what it will be ahead of time, but I don't want to have to rewrite many different lines of code in different files each time I need to change it. It is NOT user set.

So now we have Variable = ClassX

So, Let's say I set Variable to ClassA. How can I make it call ClassA using just that? For example, I know I can do this:

Variable = ClassA
if Variable == ClassA:
     # Call ClassA and run it
elif Variable == ClassB:
     # Call ClassB and run it
elif Variable == ClassC:
     # Call ClassC and run it
elif Variable == ClassD:
     # Call ClassD and run it

However, I want to do something like this:

Variable = ClassA
V = Variable()

Is this possible?

EDIT: A little more detail...

So I have 3 files that are used in this scenario.

File1.py:

# Class = ClassA
# Class = ClassB
Class = ClassC
# Class = ClassD
...
if Class == "ClassA":
    c = ClassSystem.ClassA
    short_name = c.get_short_name()
elif Class == "ClassB":
    c = ClassSystem.ClassB
    short_name = c.get_short_name()
elif Class == "ClassC":
    c = ClassSystem.ClassC
    short_name = c.get_short_name()
elif Class == "ClassD":
    c = ClassSystem.ClassD
    short_name = c.get_short_name()
...

File2.py:

from Folder.File1 import short_name
from Folder.ClassSystem import *
...
S = short_name()
S.get_information()

This doesn't seem to work. File2 is referencing the variable from file1. I then need File2 to use the variable from File1 to run the same class in ClassSystem.

Cody Dostal
  • 311
  • 1
  • 3
  • 13

2 Answers2

2

Yes, completely possible. Instead of doing it with ifs though, the most compact approach would include a dictionary of class names to class objects.

You can then key the dictionary and call the resulting class:

cls_dict = {c.__name__: c for c in {ClassA, ClassB}}
v = 'ClassA'
cls_dict[v]()

the set of classes can, of course, be altered to include any additional objects you wish.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
1

You can use eval,

c_name = 'ClassA'
obj = eval(c_name)()

but i am not sure if eval is the recommended way to do this.

Manjunath
  • 150
  • 1
  • 6