Python hasattr() function

Published February 16, 2022

The Python hasattr() method is a built-in utility function that checks if an object has the specified named attribute and returns true if it does, otherwise false.

Syntax
The Python hasattr() method has the following syntax:

getattr(object, key, default)


where:
Object: The object whose properties must be processed.
Key: an object's property
Default: the default value that must be displayed if the attribute is not found

Example

class Python:
            name = "Python3"
            version = 3
x = Python()
print("Is python present ? " + str(hasattr(x, 'name')))
print("Is version present ? " + str(hasattr(x, 'version')))

Output

Is python present ? True
Is version present ? True

 

 

Download Source code

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

224 Views