python attributes from string 1

python attributes from string

class Car : 
    color = "red"

# initializing object 
my_car = Car() 
  
# use of getattr 
print(getattr(my_car,"color"))

Here is what the above code is Doing:
1. We created a class Car.
2. We created an object my_car of the class Car.
3. We used the getattr() function to get the value of the attribute color of the object my_car.

The output of the above code will be:
red

Similar Posts