Read an attribute by name with getattr().
How It Works
getattr(instance, name, default) performs normal attribute lookup. With no default, a missing attribute raises AttributeError; with a default, a missing attribute yields that fallback, but descriptors or properties can execute code during lookup.
Untrusted attribute names should be allowlisted before accessing sensitive objects.
Step-by-Step Example
class Server:
status = "online"
server = Server()
print(getattr(server, "status"))
print(getattr(server, "location", "unknown"))
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The expression '"online"' supplies the value stored as 'status'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
online
unknown
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
Read a configurable attribute name and provide a sensible fallback.
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
- Assuming getattr() reads data without invoking properties or other descriptors.
- Using a default when an absent required attribute should raise an error.
Key Takeaways
- Read an attribute by name with getattr().
- getattr(instance, name, default) performs normal attribute lookup.
- Untrusted attribute names should be allowlisted before accessing sensitive objects.