Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python getattr() Function

Python getattr() Function

Python3 Built-in Functions Python3 built-in 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

Function description


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

Expected output:

Tom
20
Tom

Code analysis:

  1. getattr() and dot access have the same effect.
  2. 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}")

Expected output:

Tom
0
北京
属性不存在: 'Person' object has no attribute 'gender'

Code analysis:

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')}")

Result:

Running in a real environment shows the dynamically set attributes.

getattr() is a very important function in Python dynamic programming.


Python3 Built-in Functions Python3 built-in function