0

im trying to access a class method from a user input. An example would be that i want to get access the method "drive_to(destination)" from the instance "fast_bycicle" of the class "Bicycle". I want to let the user decide which bike to use so my idea kinda looks like this

class Bycicle():
   def __init__(self, color, position)
       self.color = color
       self.position = position
   def drive_to(self, destination)
       self.position = destination


fast_bycicle = Bycicle("red","home")
       


x = input("Please select a bike: ")
x = "fast_bycicle"
y = input("Please select a destination: ")
y = "Hamburg"


x.drive_to(y)

which falls short. On the other hand side id(x) returns the id of the object.

I thought about creating a list and saving the bikes names/ids to a list and access them like that but i will run into the same problem that i cant access the instance by using a string. (I might be wrong on this)

4
  • Use a dict of Bycicle instances. Commented Jul 4, 2024 at 9:35
  • Why not just use a dict with the 2 inputs in a tuple as key {("red", "home"): <object of Bycicle>}, and then, once you get the 2 inputs, invoke the drive_to() of that object? Commented Jul 4, 2024 at 9:36
  • 1
    It is very unclear what you are trying to do. The only way you can map a string to an object is via a dict. So your code should be like : mydict = {"fast_bycicle":Bycicle("red", "home")} mydict[x].drive_to(y) Commented Jul 4, 2024 at 9:37
  • Awesome! Thanks a lot, i managed to access the object by using a dictionary as you suggested. Commented Jul 4, 2024 at 9:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.