Python setattr()

Anonymous contributor's avatar
Anonymous contributor
Published Jun 13, 2023

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.

  • 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

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 the attribute.

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 property
setattr(Person, "name", "John")
# Retrieving the name property
new_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.

Code
Output

All contributors

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