Python hasattr() Function
hasattr()It is a built-in function in Python used to check whether an object has a specified attribute.
hasattr()It returns a boolean value indicating whether the object contains the specified attribute. This is very useful when handling dynamic attributes or when you need to check whether an attribute exists first.
Word Definitions: 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。
Examples
Example 1: Basic Usage
Example
class Person:
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# Check whether the attribute exists
print(hasattr(p, "name")) # Output: True
print(hasattr(p, "age")) # Output: True
print(hasattr(p, "gender")) # Output: False
# Check the 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 the attribute exists
print(hasattr(p, "name")) # Output: True
print(hasattr(p, "age")) # Output: True
print(hasattr(p, "gender")) # Output: False
# Check the method
print(hasattr(p, "name")) # Output: True
print(hasattr(p, "walk")) # Output: False
Expected Output:
True True False True False
Code Explanation:
- hasattr() checks whether an object has the specified attribute.
Example 2: Working with getattr
Example
# Safely get the attribute
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 default value")
# Output: timeout does not exist, using 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 default value")
# Output: timeout does not exist, using default value
# Dynamic check
attrs = ["debug", "port", "host"]
for attr in attrs:
if hasattr(config, attr):
print(f"{attr}: {getattr(config, attr)}")
Output:
Running in an actual environment will display the check result.
hasattr()Often used withgetattr()in conjunction with.
Other Extensions
Python3 Built-in Functions