Content · Programming · Python

Python setattr() Function: Usage and Examples

Assign an object attribute dynamically with setattr().

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Assign an object attribute dynamically with setattr().

How It Works


setattr(instance, name, value) works like assignment to an attribute whose name is stored in a string. It respects property setters and descriptors, and may be limited by __slots__ or custom __setattr__ behavior.

Direct attribute assignment is simpler when the attribute name is fixed in source code.

Step-by-Step Example


class Sensor:
    pass

sensor = Sensor()
setattr(sensor, "location", "Lab")
print(sensor.location)

Understanding the Example


  • The class groups related state and methods so each instance can manage its own values.
  • The expression 'Sensor()' supplies the value stored as 'sensor'. This value is then used or checked by the later statements.

A successful run of this example prints the following output:

Lab

Where This Fits in a Real Program


A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.

Practice: Try It Yourself


Set two known configuration attributes by validated string names.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Allowing untrusted names to overwrite internal attributes unexpectedly.
  • Assuming every class supports arbitrary new attributes despite slots or read-only properties.

Key Takeaways


  • Assign an object attribute dynamically with setattr().
  • setattr(instance, name, value) works like assignment to an attribute whose name is stored in a string.
  • Direct attribute assignment is simpler when the attribute name is fixed in source code.
Share this resourceSend this page to someone who may find it useful.