hasattr () — it is a built-in utility function in Python that is used in many day-to-day software applications.
His main task is — check if the object has the given named attribute and return true if present, false otherwise.
Syntax: hasattr (obj, key) strong >
obj: The object whose which attribute has to be checked.
key: strong> Attribute which needs to be checked.
Returns: Returns True, if attribute is present else returns False.
Code # 1: Demonstration of hasattr () work
Does name exist? True Does motto exist? False pre >
Code # 2 : Performance Analysis
< code class = "comments"> # Python code for demo
No Motto Time to execute hasattr: 5.245208740234375e-06 No Motto Time to execute try: 2.6226043701171875e-06
Applications: this function can be used to validate keys to avoid unnecessary errors when accessing missing keys. The hasattr () chaining is sometimes used to avoid entering one related attribute when there is no other.