-1

Is it possible access an instance attribute with something you can dynamically change like a variable? In the example below, you can see how I successfully access the color instance attribute with car1.color but unsuccessfully access this attribute with car1.attribute & car1[attribute].

attribute = 'color'

class Car():
    def __init__(self):
        self.color = 'red'
        self.shape = 'circle'

car1 = Car()

def f(attribute):
    print(car1.color)
    print(car1.attribute),
    print(car1[attribute])

f('color')
tonitone120
  • 1,920
  • 3
  • 8
  • 25

1 Answers1

0

You can use the function getattr

getattr(car1, 'color')
Chuk Ultima
  • 987
  • 1
  • 11
  • 21