Table of Contents
The hasattr() method returns true if an object has the given named attribute and false if it does not.
The syntax of hasattr() method is:
hasattr(object, name)
hasattr() is called by getattr() to check to see if AttributeError is to be raised or not.
1. hasattr() Parameters
hasattr() method takes two parameters:
- object – object whose named attribute is to be checked
- name – name of the attribute to be searched
2. Return value from hasattr()
hasattr() method returns:
- True, if object has the given named attribute
- False, if object has no given named attribute
3. Example: How hasattr() works in Python?
class Person:
age = 23
name = 'Adam'
person = Person()
print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))
Output
Person has age?: True Person has salary?: False
Related posts:
Python help()
Python round()
Python Set difference_update()
Python Program to Check if a Key is Already Present in a Dictionary
Python Program to Find Hash of File
Python String count()
Python Program to Print Output Without a Newline
Python Program to Differentiate Between del, remove, and pop on a List
Python abs()
Python Program to Display the multiplication Table
Python range()
Python String upper()
Python Set clear()
Python String isnumeric()
Python Program to Return Multiple Values From a Function
Intelligent Projects Using Python - Santanu Pattanayak
Python Program to Get the File Name From the File Path
Python Set symmetric_difference()
Python super()
Python sleep()
Python repr()
Python Set add()
Python Program to Sort Words in Alphabetic Order
Python enumerate()
Python Tuple index()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Get Line Count of a File
Python reversed()
Python Dictionary get()
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Find ASCII Value of Character
Python sum()