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 Get the Class Name of an Instance
Python Data Types
Python Dictionary keys()
Python Recursion
Python help()
Python staticmethod()
Machine Learning with Python for everyone - Mark E.Fenner
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Functions
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python Program to Merge Mails
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python String rpartition()
Python Program to Iterate Over Dictionaries Using for Loop
Python Program to Find Armstrong Number in an Interval
Python issubclass()
Python String isupper()
Python String translate()
Python List sort()
Python Dictionary popitem()
Python delattr()
Python List index()
Python Set difference_update()
Python Program to Find ASCII Value of Character
Python globals()
Python callable()
Python Program to Swap Two Variables
Python String isdigit()
Python min()
Python open()
Python all()
Python String isprintable()