Python getattr() Function
The getattr() function in Python is used to get the value of an attribute of an object dynamically. It's especially useful when the attribute name is stored as a string or determined at runtime.
Syntax
getattr(object, name[, default])
Parameters:
object– The object whose attribute you want to access.name– A string representing the attribute name.default(optional) – A value to return if the attribute does not exist.
Returns:
- The value of the specified attribute if it exists.
- If the attribute doesn't exist and
defaultis provided, it returnsdefault. - If the attribute doesn't exist and no
defaultis given, it raises anAttributeError.
Example: Basic Usage of getattr()
class Person:
name = "Alice"
age = 30
p = Person()
print(getattr(p, 'name'))
Alice
Why? Because 'name' is an attribute of object p.
Example: Using default Value
print(getattr(p, 'gender', 'Not Specified'))
Not Specified
This avoids an error and returns a default string if the attribute does not exist.
Use Case: Dynamic Attribute Access
attr_name = input("Enter attribute (name or age): ")
print(getattr(p, attr_name, "Attribute not found"))
Why is this useful?
- When building flexible code like dynamic APIs
- When attributes are not known ahead of time
- For reflective operations and serialization
Common Mistakes
- Passing a non-string as
namewill raise aTypeError - Not providing
defaultcan lead toAttributeErrorif attribute doesn’t exist
Interview Tip
getattr() is often used in interview questions that involve object introspection or building generic class utilities.
Summary
getattr()fetches an attribute from an object by name- Returns the attribute value if it exists
- Returns default or raises error if the attribute is missing
Practice Problem
Create a class Car with attributes brand and year. Write a program that asks the user to enter an attribute name and prints the value using getattr(). If the attribute doesn’t exist, print "Unknown attribute".
class Car:
brand = "Toyota"
year = 2022
c = Car()
attr = input("Enter attribute (brand/year): ")
print(getattr(c, attr, "Unknown attribute"))
Comments
Loading comments...