Python setattr() Function
setattr() is a built-in function in Python used to set an object's attributes.
Unlike assigning directly with dot (.) notation,setattr() lets you set an object's attributes dynamically through strings. This is very useful when the attribute to set depends on a variable name, or when dealing with unknown attributes.
Word meaning: setattr Is set attributeis short for (set attribute).
Basic syntax and parameters
Syntax format
setattr(obj, name, value)
Parameter Description
- Parameter obj:
- Type: any object
- Description: the object whose attribute is to be set.
- Parameter name:
- Type: string
- Description: the name of the attribute to set (as a string).
- Parameter value:
- Type: any value
- Description: the value to set.
Function description
- Return Value: No return value (returns
None)。 - Corresponding function: Used together with
getattr()the function,getattrwhich is used to get attributes.
Example
Example 1: basic usage
Example
Create a simple class
class
Person:
pass
Creating objects
p
=
Person
(
)
Use setattr to set an attribute
setattr
(
p
,
'name'
,
'Tom'
)
setattr
(
p
,
'age'
,
20
)
setattr
(
p
,
'city'
,
'Beijing'
)
Verify the attribute was set
(
p.
name
)
Output: Tom
(
p.
age
)
Output: 20
(
p.
city
)
Output: Beijing
Use getattr to get the attribute
(
getattr
(
p
,
'name'
)
)
Output: Tom
Expected output:
Tom
20
Beijing
Tom
Code analysis:
setattr(obj, 'name', 'Tom')is equivalent toobj.name = 'Tom'。- The attribute name is passed as a string, so it can be set dynamically.
- It can be used together with
getattr().
Example 2: setting attributes dynamically
Example
class
Student:
pass
Set several attributes dynamically
student
=
Student
(
)
fields
=
[
'name'
,
'age'
,
'grade'
,
'school'
]
values
=
[
'Lily'
,
18
,
'A'
,
'MIT'
]
for
field
,
value
in
zip
(
fields
,
values
)
:
setattr
(
student
,
field
,
value
)
Print all attributes
for
field
in
fields:
(
f
"{field}: {getattr(student, field)}"
)
Set an attribute that does not exist yet
setattr
(
student
,
'major'
,
'Computer Science'
)
(
student.
major
)
Output: Computer Science
Expected output:
name: Lily
age: 18
grade: A
school: MIT
Computer Science
Code analysis:
- Multiple attributes can be set dynamically in a loop.
- setattr can add new attributes to an object.
- This is useful when handling configuration files or user input.
Example 3: used with dict together with
Example
View the object's dict
class
Car:
def
init
(
self
)
:
self
.
brand
=
"Toyota"
car
=
Car
(
)
(
car.
dict
)
Output: {'brand': 'Toyota'}
Use setattr to add attributes
setattr
(
car
,
'model'
,
'Camry'
)
setattr
(
car
,
'year'
,
2024
)
(
car.
dict
)
Output: {'brand': 'Toyota', 'model': 'Camry', 'year': 2024}
Check whether an attribute exists
if
hasattr
(
car
,
'brand'
)
:
(
f
"Brand: {getattr(car, 'brand')}"
)
Expected output:
{'brand': 'Toyota'}
{'brand': 'Toyota', 'model': 'Camry', 'year': 2024}
品牌: Toyota
setattr() It is typically used together with the getattr()、hasattr()、delattr() used together, they form a complete toolkit for attribute operations.
Python3 built-in function