Python setattr()
Anonymous contributor
Published Jun 13, 2023
Contribute to Docs
The setattr() function is a built-in Python function used to set the value of a named attribute of an object. It allows a developer to dynamically assign or modify attributes of an object at runtime.
Syntax
setattr(object, attribute, value)
The setattr() function requires three parameters:
object: an object.attribute: name of the attribute to be set.value: the value to give theattribute.
Example
The following example will change the value of the name attribute of the Person object:
class Person:name = "Alex"age = 30# Updating the name propertysetattr(Person, "name", "John")# Retrieving the name propertynew_name = getattr(Person, "name")print("My new name is " + new_name)
The code results in the following output:
My new name is John
Codebyte Example
Suppose there is a Person class that represents a person with attributes such as name and age. The setattr() function can be used to dynamically set the value of an attribute.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours