Python setattr() Function

Python3 内置函数Python3 Built-in Functions


setattr()is a built-in function in Python used to set object attributes.

Unlike directly using dot (.) notation for assignment,setattr()it allows you to dynamically set object attributes through strings. This is very useful when you need to set attributes based on variable names or handle unknown attributes.

Word Definition: setattrYesset attributeabbreviation 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 (in string form).
  • Parameter value:
    • Type: Any value
    • Description: The value to set.

Function Description

  • Return value: No return value (returnsNone)。
  • Corresponding function: Used withgetattr()together with the function,getattrused to get attributes.

Examples

Example 1: Basic Usage

Example

# Create a simple class
class Person:
    pass

# Create an object
p = Person()

# Use setattr to set attributes
setattr(p, 'name', 'Tom')
setattr(p, 'age', 20)
setattr(p, 'city', 'Beijing')

# Verify the attribute has been set
print(p.name)    # Output: Tom
print(p.age)     # Output: 20
print(p.city)    # Output: Beijing

# Use getattr to get attributes
print(getattr(p, 'name'))  # Output: Tom

Expected Output:

Tom
20
Beijing
Tom

Code Analysis:

  1. setattr(obj, 'name', 'Tom')Equivalent toobj.name = 'Tom'。
  2. The attribute name is passed as a string, allowing dynamic setting.
  3. Can be used withgetattr()together.

Example 2: Dynamically Setting Attributes

Example

class Student:
    pass

# Dynamically set multiple attributes
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:
    print(f"{field}: {getattr(student, field)}")

# Set a non-existent attribute
setattr(student, 'major', 'Computer Science')
print(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 through a loop.
  • setattr can add new attributes to an object.
  • This is useful when handling configuration files or user input.

Example 3: Working with __dict__

Example

# View the object's __dict__
class Car:
    def __init__(self):
        self.brand = "Toyota"

car = Car()
print(car.__dict__)  # Output: {'brand': 'Toyota'}

# Use setattr to add attributes
setattr(car, 'model', 'Camry')
setattr(car, 'year', 2024)

print(car.__dict__)  # Output: {'brand': 'Toyota', 'model': 'Camry', 'year': 2024}

# Check if the attribute exists
if hasattr(car, 'brand'):
    print(f"Brand: {getattr(car, 'brand')}")

Expected Output:

{'brand': 'Toyota'}
{'brand': 'Toyota', 'model': 'Camry', 'year': 2024}
品牌: Toyota

setattr()Usually used withgetattr()、hasattr()、delattr()together, forming a complete toolset for attribute operations.


Python3 内置函数Python3 Built-in Functions


Other Extensions