English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python hasattr() usage and examples

Python built-in functions

If the object has the given named attribute, the hasattr() method returns true, otherwise it returns false.

The syntax of the hasattr() method is:

hasattr(object, name)

The hasattr() method is called by getattr() to check whether AttributeError is raised.

hasattr() parameters

The hasattr() method takes two parameters:

  • object -The object to check for named attributes

  • name -The name of the property to search for

hasattr() return value

The hasattr() method returns:

  • TrueIf the object has the given defined attribute

  • FalseIf the object does not have the given defined attribute

Example: How does hasattr() work in Python?

class Person:
    age = 23
    name = 'Adam'
person = Person()
print('Person has an age attribute?:', hasattr(person, 'age'))
print('Person has a salary attribute?:', hasattr(person, 'salary'))

When running the program, the output is:

Person has an age attribute?: True
Person has a salary attribute?: False

Python built-in functions