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 Program to Measure the Elapsed Time in Python
Intelligent Projects Using Python - Santanu Pattanayak
Python sorted()
Python Program to Differentiate Between type() and isinstance()
Python isinstance()
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Get a Substring of a String
Python Program to Convert Kilometers to Miles
Python Dictionary get()
Python id()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Find the Largest Among Three Numbers
Python String isnumeric()
Python Set intersection_update()
Python Function Arguments
Python break and continue
Python getattr()
Python hex()
Python String count()
Python String islower()
Python open()
Python Program to Merge Two Dictionaries
Python Set remove()
Python String partition()
Deep Learning in Python - LazyProgrammer
Python if...else Statement
Python eval()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Capitalize the First Character of a String
Python Program to Find the Sum of Natural Numbers
Python dict()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili