-2

I am adding car function entry to the class but it is not working.

    class car():
      def __init__(self,speed,engine,color):
         self.speed = speed
         #ı add speed
         self.engine = engine
         #ı add engine
         self.color = color
         #ı add color
         print("new car add")
    car1 = car(233,23,"red")
    car2 = car(300,59,"yellow")
    car3 = car(32,23,"blue")
    a = int(input("car number: "))
    b = str(input("type : speed , engine , color: ")) 
    a = str(a)
    #make car + a
    #maybe here is broken
    no = "car" + a
    nu = no + "." + b
    print(nu)

How do I get the color of car #1 when a == 1 and b == "color"?

r00tz
  • 1

2 Answers2

0
  1. You want a list of car objects, not a bunch of numbered variables.

    cars = [car(233,23,"red"),
            car(300,59,"yellow"),
            car(32,23,"blue")
    ] 
    
  2. Use getattr to get an attribute using a variable that contains the name of the attribute.

    >>> a = 1; b = "color"; getattr(cars[a], b)
    'red'
    
chepner
  • 497,756
  • 71
  • 530
  • 681
0

In the case that a='1' and b='color':

then

nu = "car1.color"

This is a string, but what you would like is for python to evaluate and run it as an expression.

You can use eval() to do this. Try:

print(eval(nu))

However, I would suggest a better approach is using a list as @chepner suggested, or a dictionary.

Oceanescence
  • 1,967
  • 3
  • 18
  • 28