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 List Comprehension
Python String ljust()
Python type()
Python Set clear()
Python Program to Display Calendar
Python ord()
Python iter()
Python Program to Get the Class Name of an Instance
Python Program to Find LCM
Python Program to Iterate Through Two Lists in Parallel
Python set()
Python Program to Check Armstrong Number
Python dict()
Python Shallow Copy and Deep Copy
Python String startswith()
Python Program to Split a List Into Evenly Sized Chunks
Python for Loop
Python Program to Check if a Key is Already Present in a Dictionary
Python complex()
Python float()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Function Arguments
Python Program to Convert Bytes to a String
Python abs()
Python hash()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python isinstance()
Python Program to Print all Prime Numbers in an Interval
Python Program to Merge Mails
Python String swapcase()
Python Program to Extract Extension From the File Name
Python str()