setattr()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
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 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.

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy