Use app×
QUIZARD
QUIZARD
JEE MAIN 2026 Crash Course
NEET 2026 Crash Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
528 views
in Python by (178k points)
Python setattr() Function

Please log in or register to answer this question.

1 Answer

0 votes
by (178k points)

The setattr() function in Python is used to set the value of a named attribute of an object. It takes three parameters:

setattr(obj, name, value)
 

where,

  • obj: the object whose attribute is to be set.
  • name: the name of the attribute to be set.
  • value: the value to be assigned to the attribute.

Here is an example of using setattr():

class MyClass:
    pass

my_obj = MyClass()

setattr(my_obj, 'my_attribute', 42)

print(my_obj.my_attribute)  # output: 42
 

In the above example, we create an instance of the MyClass class and then use the setattr() function to set the value of its attribute named 'my_attribute' to 42. We then print the value of the attribute using the dot notation.

Note that you can also set attributes of built-in types such as lists, dictionaries, and strings using the setattr() function. However, it is more commonly used to set attributes of custom classes.

Related questions

0 votes
1 answer
asked Feb 20, 2022 in Programming by DivyansheeSahoo (120k points)
0 votes
1 answer
asked Aug 19, 2023 in Python by MAhmad (120 points)
0 votes
1 answer
asked Aug 18, 2023 in Python by MAhmad (120 points)
+1 vote
1 answer
asked Aug 18, 2023 in Python by MAhmad (120 points)
0 votes
1 answer
asked Aug 18, 2023 in Python by MAhmad (120 points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...