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 Dictionary setdefault()
Python Program to Find the Factorial of a Number
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Generate a Random Number
Python Program to Return Multiple Values From a Function
Python Program to Check if a Key is Already Present in a Dictionary
Python del Statement
Python Program to Find Hash of File
Python Program to Delete an Element From a Dictionary
Python bytearray()
Python Program to Check the File Size
Python Program to Append to a File
Python Global, Local and Nonlocal variables
Python Dictionary clear()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Program to Calculate the Area of a Triangle
Python reversed()
Python String translate()
Python Program to Trim Whitespace From a String
Python Program to Convert Celsius To Fahrenheit
Python List reverse()
Python delattr()
Python String isprintable()
Python classmethod()
Python Program to Print Hello world!
Python Set symmetric_difference()
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python Numbers, Type Conversion and Mathematics
Python Program to Remove Punctuations From a String
Python break and continue
Python Dictionary keys()