Python Programmer
Python Programmer

Reputation: 25

How to reference a class from a string which is part of a variable 3.7

I have just read a text file and extracted a string and stored it as a variable. This string also happens to be the name of a class I want to reference in order to use in a function for example. The "which_class" variable is the whichever class was stored in the file

I tried passing the which_class variable in as a parameter to the function. Removing the quotations seems to make it work but I am unsure how to do this.

class needed_for_func_one():
    multiplier = 1.23

class needed_for_func_two():
    multiplier = 1.15


def random_function(which_class):
    print(123 * which_class.multiplier)

PSEUDO CODE
READ FROM FILE STORE STRING AS "which_class"

which_class = "needed_for_func_two"


random_function(which_class)

But this didn't work it just gave me an attribute error

Upvotes: 0

Views: 42

Answers (3)

prhmma
prhmma

Reputation: 953

first, to use a class you need an object of a class. so if what you read is a name of the class or any other thing it does not matter, just use an if statement to decide what is inside that variable so-called "which_class". then create an object like :

if which_class=="needed_for_func_one":
    newObject = needed_for_func_one()
elseif which_class=="needed_for_func_two":
    newObject = needed_for_func_two()

then use the print like :

print(123 * newObject.multiplier )

Upvotes: 0

Stefan
Stefan

Reputation: 160

I think your question is related to this one How you call the function depends if it is a global function or if it is inside an object.

globals()['call_this_function']() # this is probably what you need

or

getattr(from_this_object, 'call_this_function')()

Upvotes: 0

Johannes
Johannes

Reputation: 118

the eval function could help you here.

random_function(eval(whichClass))

However, you should probably rethink whether you really want to it that way or if there is a much cleaner solution.

Upvotes: 1

Related Questions