Python Tutorial Python Advanced Python References Python Libraries

Python hasattr() Function



The Python hasattr() function is used to check whether the specified object has specified attribute or not. It returns true when specified object has specified attribute, else returns false.

Syntax

hasattr(object, attribute)

Parameters

object Required. An object
attribute Required. Specify attribute which need to checked in object.

Example:

In the example below, hasattr() function is used to check the specified attribute is present in the given class or not.

class MyClass:
   name = 'John'
   age = 25
   city = 'London'

print(hasattr(MyClass, 'age'))
print(hasattr(MyClass, 'hobby'))

The output of the above code will be:

True
False

❮ Python Built-in Functions