Python getattr() Function
getattr()It is a built-in function in Python used to get object attribute values.
getattr()It allows us to dynamically access object attributes rather than using dot notation (.) for static access. This is very useful when dealing with unknown attributes.
Word Definitions: 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 to be obtained.
- Parameter name:
- Type: String
- Description: 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 value of the attribute.
- Exceptions: If the attribute does not exist and no default value is provided, an AttributeError will be raised.
Examples
Example 1: Basic Usage
Example
class Person:
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Get attribute
print(getattr(p, "name")) # Output: Tom
print(getattr(p, "age")) # Output: 20
# Using dot notation
print(p.name) # Output: Tom
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Get attribute
print(getattr(p, "name")) # Output: Tom
print(getattr(p, "age")) # Output: 20
# Using dot notation
print(p.name) # Output: Tom
Expected output:
Tom 20 Tom
Code explanation:
- getattr() and dot notation access have the same effect.
- The advantage of getattr() is that you can specify the attribute name with a string.
Example 2: Using Default Value
Example
class Person:
def __init__(self):
self.name = "Tom"
p = Person()
# Get an existing attribute
print(getattr(p, "name", "unknown")) # Output: Tom
# Get a non-existent attribute (with default value)
print(getattr(p, "age", 0)) # Output: 0
print(getattr(p, "city", "Beijing")) # Output: Beijing
# Get a non-existent attribute (without 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", "unknown")) # Output: Tom
# Get a non-existent attribute (with default value)
print(getattr(p, "age", 0)) # Output: 0
print(getattr(p, "city", "Beijing")) # Output: Beijing
# Get a non-existent attribute (without 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 explanation:
- The third parameter provides a default value to avoid exceptions.
- This is useful when dealing with optional attributes.
Example 3: Dynamic Access
Example
# Dynamically select attribute
data = {"name": "Tom", "age": 20}
field = "name"
print(getattr(data, field)) # Access via string
# Used with setattr
class Person:
pass
p = Person()
# Dynamically set attribute
fields = ["name", "age", "city"]
values = ["Tom", 20, "Beijing"]
for field, value in zip(fields, values):
setattr(p, field, value)
# Dynamically get all attributes
for field in fields:
print(f"{field}: {getattr(p, field)}")
# hasattr combined with getattr
if hasattr(p, "name"):
print(f"Name is: {getattr(p, 'name)}")
data = {"name": "Tom", "age": 20}
field = "name"
print(getattr(data, field)) # Access via string
# Used with setattr
class Person:
pass
p = Person()
# Dynamically set attribute
fields = ["name", "age", "city"]
values = ["Tom", 20, "Beijing"]
for field, value in zip(fields, values):
setattr(p, field, value)
# Dynamically get all attributes
for field in fields:
print(f"{field}: {getattr(p, field)}")
# hasattr combined with getattr
if hasattr(p, "name"):
print(f"Name is: {getattr(p, 'name)}")
Output:
Running in an actual environment will display the dynamically set attribute.
getattr()It is a very important function in Python dynamic programming.
Other Extensions
Python3 Built-in Functions