Python hasattr() Function
Description
hasattr()The function is used to determine whether the object contains the corresponding attribute.
Syntax
hasattr syntax:
hasattr(object, name)
Parameters
- object -- The object.
- name -- A string, the attribute name.
Return Value
Returns True if the object has the attribute, otherwise returns False.
Example
The following example demonstrates the usage of hasattr:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no')) # Does not have this attribute
Output:
True True True FalseOther Extensions
Python Built-in Functions