23. Problem to example of setattr and getattr in Python

In this Python oops program, we will create a class to show example of setattr and getattr in Python. This example demonstrates how to dynamically set and get instance variables using the setattr and getattr in Python functions.

Setattr and getattr in Python

Steps to solve the program
  1. The code defines a class named MyClass with an empty constructor (__init__ method).
  2. An instance of the MyClass class is created and assigned to the variable obj.
  3. The setattr function is used to dynamically set an instance variable on the obj object. The first argument to setattr is the object on which we want to set the variable (obj), the second argument is the name of the variable as a string (“variable”), and the third argument is the value we want to assign to the variable (“Value”).
  4. The getattr function is used to dynamically get the value of an instance variable from the obj object. The first argument to getattr is the object from which we want to get the variable value (obj), and the second argument is the name of the variable as a string (“variable”). The value of the variable is then assigned to the value variable.
  5. Finally, the value of the instance variable is printed, which will output “Value” in this case.

				
					class MyClass:
    def __init__(self):
        pass

# Create an object of the class
obj = MyClass()

# Set instance variable dynamically
setattr(obj, "variable", "Value")

# Get instance variable dynamically
value = getattr(obj, "variable")
print(value)

				
			

Output:

				
					Value
				
			

Related Articles

Create 5 Python classes and set up multilevel inheritance among all the classes.

Python oops program with encapsulation.

Leave a Comment