Let's say I have a class and an object of said class:
class Rock:
def __init__(self, name, group):
self.name = name
self.group = group
granite = Rock('Granite', 'Igneous')
Now let's say I want the user to input a rock, so I have a line such as this:
rock = input('Type the name of a rock: ')
Based on what rock the user inputs, I want it to print out a string such as, "Granite belongs to the igneous group." I can achieve this string by typing:
print(granite.name + ' belongs to the ' + granite.group + ' group.')
However, this only gives the illusion of choice, as if the user types any rock besides granite, they will be puzzled as to why the only output is about granite. Ideally, I would like to be able to type something like:
print(rock.name + ' belongs to the ' + rock.group + ' group.')
Where no matter what the user inputs, if there's an object with a variable equal to that string, the rock variable will now be equal to said rock object. However, this doesn't work because the user is inputting a string, and not a variable class. I can get around this by adding an if statement such as:
if rock == 'granite':
rock = granite
Though, if I do that, then I would have to write an if statement for EVERY rock object I have, and if I have A LOT of rock classes, this would be very inefficient. So my question is, is there a way to have the user input an actual variable instead of just a string? If not, any advice on how to do this would be appreciated.
Elaborating @Barmar's suggestion. Use a dictionary:
rocks = {"granite": Rock('Granite', 'Igneous'), ....}
rock_name = input('Type the name of a rock: ')
rock = rocks[rock_name.lower()] # As long as it is a valid name
You may not even need Rock.name anymore.
Put all the rocks in a dictionary so you can look them up by name.
class Rock:
all_rocks = {}
def __init__(self, name, group):
self.name = name
self.group = group
self.all_rocks[name] = self
granite = Rock('Granite', 'Igneous')
rock_name = input("Type the name of a rock")
rock = Rock.all_rocks.get(rock_name)
print(rock.group)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With