Python hasattr Function with Examples - Python Tutorial | Logic Practice
Python Course / Other / Python hasattr Function with Examples

Python hasattr Function with Examples

BLUF: This lesson on Python hasattr Function with Examples provides a comprehensive guide to understanding and implementing this concept in Python. Whether you're a beginner or looking to refresh your knowledge, you'll find clear explanations and interactive code examples here.
Key Concept: Python hasattr Function with Examples

Mastering Python hasattr Function with Examples is essential for building efficient Python applications. Focus on the syntax and the best practices highlighted in this tutorial.

The Python function hasattr evaluates to true when an object possesses the specified named attribute. Conversely, it yields false if the attribute is not present.

Python hasattr Function Syntax

It has the following syntax:

Example

hasattr(object, attribute)

Parameters

  • object: It is an object whose named attribute is to be checked.
  • attribute: It is the name of the attribute that you want to search.
  • Return

It will return true if the specified object possesses the attribute with the provided name. If the attribute does not exist, it will return false.

Python hasattr Function Example

The example presented below demonstrates how the hasattr function operates in Python.

Example

class Employee:

    age = 21

    name = 'Phill'

employee = Employee()

print('Employee has age?:', hasattr(employee, 'age'))

print('Employee has salary?:', hasattr(employee, 'salary'))

Output:

Output

Employee has age?: True

Employee has salary?: False

Explanation:

In the preceding example, we defined a class called Employee, and subsequently, we instantiated an object of the Employee class, referred to as employee. The expression hasattr(employee, 'age') evaluates to true since the employee object possesses an attribute named age. Conversely, hasattr(employee, 'salary') yields a false value because the employee object does not include an attribute named salary.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience