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 issubclass()
Python String istitle()
Python Program to Access Index of a List Using for Loop
Python Dictionary popitem()
Python input()
Python sorted()
Python repr()
Python String isspace()
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Parse a String to a Float or Int
Python Shallow Copy and Deep Copy
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Check Leap Year
Python Program to Transpose a Matrix
Python ord()
Python Custom Exceptions
Python Program to Merge Two Dictionaries
Python List copy()
Python Program to Find Factorial of Number Using Recursion
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python getattr()
Python Program to Find ASCII Value of Character
Python Program to Print Hello world!
Python Program to Count the Occurrence of an Item in a List
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Create Pyramid Patterns
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python List sort()
Python Program to Create a Long Multiline String
Python Program to Find the Size (Resolution) of a Image
Python Program to Return Multiple Values From a Function
Python Program to Add Two Matrices