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
- The code defines a class named MyClass with an empty constructor (__init__ method).
- An instance of the MyClass class is created and assigned to the variable obj.
- 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”).
- 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.
- 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
Python oops program with encapsulation.
Create a Python class called Rectangle with attributes length and width.
Create a Python class called Circle with attributes radius.
Create a Python class called Person with attributes name and age.
Create a Python class called Student that inherits from the Person class.
Create a Python class called Cat that inherits from the Animal class.