English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial de Python Básico

Python flow control

Função do Python

Tipos de Dados do Python

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python setattr() usage and example

Python built-in functions

The setattr() function sets the value of the object's attribute.

The syntax of setattr() function is:

setattr(object, name, value)

If you want to get the attribute of an object, please usegetattr().

setattr() parameters

The setattr() function has three parameters:

  • object -The object that must be set for the attribute

  • name -Attribute name

  • value -The value assigned to the attribute

setattr() return value

The setattr() method does not return anything. Returns None.

Example1How setattr() works in Python?

class Person:
    name = 'Adam'
    
p = Person()
print('Before modification:', p.name)
# Set the name to 'John'
setattr(p, 'name', 'John')
print('After modification:', p.name)

Output result

Before modification: Adam
After modification: John

Example2When the attribute is not found in setattr()

If the attribute is not found, setattr() creates a new attribute and assigns a value to it. However, this can only be done if the object implements the __dict__() method.

You can usedir()The function checks all properties of the object.

class Person:
    name = 'Adam'
    
p = Person()
# Set the attribute name to John
setattr(p, 'name', 'John')
print('Name is:', p.name)
# Set a non-existent attribute in Person
setattr(p, 'age', 23)
print('Age is:', p.age)

Output result

Name is: John
Age is: 23

Python built-in functions