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 String splitlines()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Operator Overloading
Python Program to Measure the Elapsed Time in Python
Python Matrices and NumPy Arrays
Python Program to Calculate the Area of a Triangle
Python Program to Get the Class Name of an Instance
Python String find()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String split()
Python bin()
Python Numbers, Type Conversion and Mathematics
Python bool()
Python Global, Local and Nonlocal variables
Python Program to Convert Two Lists Into a Dictionary
Python input()
Python Program to Create a Countdown Timer
Python List count()
Python Set difference_update()
Python Multiple Inheritance
Python String upper()
Python Program to Print all Prime Numbers in an Interval
Python Program to Find HCF or GCD
Python Errors and Built-in Exceptions
Python Program to Differentiate Between type() and isinstance()
Python any()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Display Fibonacci Sequence Using Recursion
Python Dictionary update()
Python sorted()
Python Program to Display the multiplication Table
Python float()