Python getattr() Function
getattr() is a built-in Python function that gets the value of an object attribute.
getattr() It lets us access an object's attributes dynamically instead of using dot (.) static access. This is very useful when dealing with unknown attributes.
Word meaning: getattr 是 get attribute(获取属性)的缩写。
Basic syntax and parameters
Syntax format
getattr(object, name) getattr(object, name, default)
Parameter Description
- Parameter object:
- Type: any object
- Description: the object whose attribute is wanted.
- Parameter name:
- Type: string
- Description: the attribute name.
- Parameter default(optional):
- Type: any value
- Description: the default value returned if the attribute does not exist.
Function description
- Return Value: returns the attribute's value.
- exception: if the attribute does not exist and no default is given, an AttributeError is raised.
Example
Example 1: basic usage
Example
class Person:
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Get an attribute
print(getattr(p, "name")) # Output: Tom
print(getattr(p, "age")) # Output: 20
# Use dot notation
print(p.name) # Output: Tom
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Get an attribute
print(getattr(p, "name")) # Output: Tom
print(getattr(p, "age")) # Output: 20
# Use dot notation
print(p.name) # Output: Tom
Expected output:
Tom 20 Tom
Code analysis:
- getattr() and dot access have the same effect.
- The advantage of getattr() is that the attribute name can be given as a string.
Example 2: using a default value
Example
class Person:
def __init__(self):
self.name = "Tom"
p = Person()
# Get an existing attribute
print(getattr(p, "name", "File %s type is: %s%n")) # Output: Tom
# Get a non-existent attribute (with a default value)
print(getattr(p, "age", 0)) # Output: 0
print(getattr(p, "city", "Beijing")) # Output: Beijing
# Get a non-existent attribute (without a default value)
try:
print(getattr(p, "gender"))
except AttributeError as e:
print(f"Attribute does not exist: {e}")
def __init__(self):
self.name = "Tom"
p = Person()
# Get an existing attribute
print(getattr(p, "name", "File %s type is: %s%n")) # Output: Tom
# Get a non-existent attribute (with a default value)
print(getattr(p, "age", 0)) # Output: 0
print(getattr(p, "city", "Beijing")) # Output: Beijing
# Get a non-existent attribute (without a default value)
try:
print(getattr(p, "gender"))
except AttributeError as e:
print(f"Attribute does not exist: {e}")
Expected output:
Tom 0 北京 属性不存在: 'Person' object has no attribute 'gender'
Code analysis:
- The third argument provides a default value, avoiding an exception.
- This is useful when dealing with optional attributes.
Example 3: dynamic access
Example
# Select an attribute dynamically
data = {"name": "Tom", "age": 20}
field = "name"
print(getattr(data, field)) # Access via a string
# Combine with setattr
class Person:
pass
p = Person()
# Set an attribute dynamically
fields = ["name", "age", "city"]
values = ["Tom", 20, "Beijing"]
for field, value in zip(fields, values):
setattr(p, field, value)
# Get all attributes dynamically
for field in fields:
print(f"{field}: {getattr(p, field)}")
# hasattr combined with getattr
if hasattr(p, "name"):
print(f"The name is: {getattr(p, 'name')}")
data = {"name": "Tom", "age": 20}
field = "name"
print(getattr(data, field)) # Access via a string
# Combine with setattr
class Person:
pass
p = Person()
# Set an attribute dynamically
fields = ["name", "age", "city"]
values = ["Tom", 20, "Beijing"]
for field, value in zip(fields, values):
setattr(p, field, value)
# Get all attributes dynamically
for field in fields:
print(f"{field}: {getattr(p, field)}")
# hasattr combined with getattr
if hasattr(p, "name"):
print(f"The name is: {getattr(p, 'name')}")
Result:
Running in a real environment shows the dynamically set attributes.
getattr() is a very important function in Python dynamic programming.
Python3 built-in function