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

Python hasattr() Function

Python hasattr() Function

Python3 Built-in Functions Python3 built-in function


hasattr() is a built-in Python function that checks whether an object has a specified attribute.

hasattr() It returns a boolean indicating whether the object contains the specified attribute. This is very useful when handling dynamic attributes or when the existence of an attribute must be checked first.

Word meaning: hasattr 是 has attribute(有属性)的缩写。


Basic syntax and parameters

Syntax format

hasattr(object, name)

Parameter Description

Function description


Example

Example 1: basic usage

Example

class Person:
    def __init__(self):
        self.name = "Tom"
        self.age = 20

p = Person()

# Check whether an attribute exists
print(hasattr(p, "name"))    # Output: True
print(hasattr(p, "age"))     # Output: True
print(hasattr(p, "gender"))  # Output: False

# Check a method
print(hasattr(p, "name"))          # Output: True
print(hasattr(p, "walk"))          # Output: False

Expected output:

True
True
False
True
False

Code analysis:

  1. hasattr() checks whether an object has a specified attribute.

Example 2: combined with getattr

Example

# Get an attribute safely
class Config:
    def __init__(self):
        self.debug = True
        self.port = 8080

config = Config()

# Check first, then get
if hasattr(config, "debug"):
    print(f"debug: {config.debug}")

if hasattr(config, "timeout"):
    print(f"timeout: {config.timeout}")
else:
    print("timeout does not exist, using the default value")
    # Output: timeout does not exist, using the default value

# Dynamic check
attrs = ["debug", "port", "host"]
for attr in attrs:
    if hasattr(config, attr):
        print(f"{attr}: {getattr(config, attr)}")

Result:

Running in a real environment shows the check results.

hasattr() Often used together with getattr() .


Python3 Built-in Functions Python3 built-in function