Questions

What is Getattr and Setattr in Python?

Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.

Syntax

                    

setattr(object, name, value)

where,

value = value to be set for the attribute

Example

                    

# Python program to illustrate setattr() function
class Details:
    name = 'Sam'
    age = 24

# Create an object of the class
d = Details()

print('Name before modification:', d.name)
print('Age before modification:', d.age)

setattr(d, 'name', 'Timmy')
setattr(d, 'age', 27)

print('Name after modification:', d.name)
print('Age after modification:', d.age)

Output

                    

Name before modification: Sam
Age before modification: 24

Name after modification: Timmy
Age after modification: 27

Related Questions

Related Topics

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

avatar
  Subscribe  
Notify of

Customize your course in 30 seconds

Which class are you in?
No thanks.