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 Last Element of the List
Python Type Conversion and Type Casting
Python String center()
Python Program to Extract Extension From the File Name
Python print()
Python str()
Python Program to Find Factorial of Number Using Recursion
Python staticmethod()
Python Program to Copy a File
Python Recursion
Python String isalpha()
Python Program to Print Output Without a Newline
Python Dictionary copy()
Python Anonymous / Lambda Function
Python Generators
Python Program to Remove Punctuations From a String
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python next()
Python Dictionary
Python Program to Check Whether a String is Palindrome or Not
Python min()
Node.js vs Python for Backend Development
Python sorted()
Python Decorators
Python String splitlines()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python String casefold()
How to Get Started With Python?
Python Variables, Constants and Literals
Python Program to Sort Words in Alphabetic Order
Python String format()
Python Program to Illustrate Different Set Operations