The Python hasattr() function returns TRUE if an object has a specific attribute name.
If the attribute name is not defined, False is returned.
hasattr() function example
In this example a class Dog has two attributes: age and name.
The hasattr() function is used to test for name and breed attributes.
# hasattr() function example
age = 5
name = 'milo'
milo = Dog()
print('Dog has a name: ', hasattr(milo, 'name'))
print('Dog has a breed: ', hasattr(milo, 'breed'))
The code defined a name for the Dog class but not a breed. Therefore the first hasattr() call equals True, and the second hasattr() call equals False.
Dog has a name: True
Dog has a breed: False
The syntax of the hasattr() function is:
The hasattr() function takes two arguments: The object for which the attribute is checked and the name of the attribute to be checked. Both arguments are required. If less than two arguments or more than two arguments are given, an TypeError exception is raised.
TypeError: hasattr expected 2 arguments, got 1
hasattr() return value
The hasattr() function returns a boolean value:
True, if the given object has the given attribute name
False, if the given object has not the given attribute name
|object has attribute name
|object has not attribute name
The hasattr() function has two related functions:
The dir() function
can be used to print all existing attributes of an object.
The delattr() function
can be used to delete a specific attribute.