'Can I access an instance attribute dynamically with something like a variable? [duplicate]

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')


Solution 1:[1]

You can use the function getattr

getattr(car1, 'color')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chuk Ultima