How to target a specific instance of a class from a string variable

Viewed 133

I have a program where I need to get information from one of many instances of a class from just a string variable.

I've asked a programmer friend of mine for help but he's specialised in C# rather than python3 so the best he could offer was to try using the exec() command. This didn't really help me.

Say I have some code setting up information about cars

class Cars:
    def __init__(self, Brand, Model, Owner):
        self.Brand = Brand
        self.Model = Model
        self.Owner = Owner

Car1 = Cars("Honda", "Civic", "Jon Arbuckle")

Car2 = Cars("Ford", "Focus", "Martha Jones")

MysteryCar = "Car1"

Is there anyway to return the value "Jon Arbuckle" from only knowing what's stored in MysteryCar?

2 Answers

using locals() which is a dict of you local scope's variables' names (as strings) as its keys and their values as.....well its values!

print(locals()[MysteryCar].Owner)

Another alternative would be to use eval which is a method that evaluates a string as python code. So you could do something like:

print(eval(MysteryCar).Owner)

But in general eval is considered risky and should be avoided, in my opinion...

For example if your MysteryCar is an input from the user that could lead to serious problems if the user puts in some dangerous command.

On the other hand, using locals you could let the user know if his selection is wrong using try/except KeyError

Your friend is correct. You can use exec to run some Python code which you define using the string that MysteryCar is pointing to. I like f-strings (Python 3.6+) but you can format your strong in other ways, too:

>>> command = f"car_owner = {MysteryCar}.Owner"
>>> exec(command)
>>> print(car_owner)
Jon Arbuckle

MysteryCar will evaluate to Car1 inside the f-string, so you're executing the command

car_owner = Car1.Owner

above.

As some comments pointed out, however, I would question whether this is the best solution to the problem, or if you should just use a dictionary.

Related