[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 242
  • Last Modified:

Really dynamic Python command

Hello experts,

In Python, I have classes called A, B, ... X. I also have a string variable StringClassName which holds the name of the class I would like to create an instance of.

I don't want to have a million chained if sentences that each checks the content of StringClassName, I would much rather be able to somehow do new_class_instance = StringClassName(), which does not work since a string object is not callable.

If this is not possible, it would be great if you could tell me why.

I hope I am clear enough about my question.
0
mannsi
Asked:
mannsi
1 Solution
 
Hamed ZaghaghiCommented:
Hi,

simply use this:

a = globals()['ClassName']
instead of
a = ClassName
0
 
mannsiAuthor Commented:
Judging by the ugly syntax, I take it that this method is not widely used, right ? Do people simply use chained ifs ?
0
 
HonorGodCommented:
For a very small number of items, a nested if/then/else might be used.
However, for any non-trivial number of classes, the syntax shown by zaghaghi is more concise, and accurate.
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now