python hasattr
时间: 2024-05-06 19:19:31 浏览: 83
python基于exchange函数发送邮件过程详解
`hasattr()` is a built-in Python function that returns a boolean value indicating whether an object has a given attribute or not.
Syntax:
```
hasattr(object, attribute)
```
Parameters:
- `object`: The object to check for the attribute.
- `attribute`: A string representing the name of the attribute to check.
Return Value:
- `True`: If the object has the specified attribute.
- `False`: If the object does not have the specified attribute.
Example:
```
class MyClass:
def __init__(self):
self.my_attribute = "Hello, World!"
obj = MyClass()
# Check if obj has the attribute "my_attribute"
if hasattr(obj, "my_attribute"):
print(obj.my_attribute) # Output: "Hello, World!"
# Check if obj has the attribute "non_existing_attribute"
if hasattr(obj, "non_existing_attribute"):
print("This should not be printed")
else:
print("The attribute does not exist") # Output: "The attribute does not exist"
```
阅读全文