Python hasattr()

In this post, we will see about Python hasattr() method.
Python hasattr() method returns true if name attribute is present in object. If attribute is not present then it returns false.


Syntax

As you can see it takes three arguments
object: It is the object whose named attribute you want to check
name: It is the name of attribute


Return

It returns the true or False depending on availability of named attribute.


Example

Let’s see with the help of simple example.

class Customer: name = 'John' age = 25 customer = Customer() print("is name attribute present:",hasattr(customer,'name')) print("is address attribute address:",hasattr(customer,'address'))

Output:

is name attribute present: True
is name attribute address: False

hasattr internally uses getAttr() to chgetattreck if attribute is present or not.
That’s all about Python hasattr() function.

Leave a Reply

Your email address will not be published. Required fields are marked *