Python hasattr() 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
- Parameter object:
- Type: any object
- Description: the object to check.
- Parameter name:
- Type: string
- Description: the attribute name.
Function description
- Return Value: returns a boolean value
TrueorFalse。
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
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:
- 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)}")
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 function