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 Object Oriented Programming
Python Program to Append to a File
Python any()
Python Program to Access Index of a List Using for Loop
Python Decorators
Python Set issuperset()
Python Anonymous / Lambda Function
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Set update()
Python File I/O Operation
Python String count()
Python Program to Shuffle Deck of Cards
Python String zfill()
Python Program to Check Leap Year
APIs in Node.js vs Python - A Comparison
Python Program to Get the File Name From the File Path
Python Program to Print the Fibonacci sequence
Python Program to Find the Factorial of a Number
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Program to Randomly Select an Element From the List
Python List extend()
Python Modules
Python String maketrans()
Python Set symmetric_difference()
Python String swapcase()
Python Program to Merge Mails
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Tuple
Python Program to Find Numbers Divisible by Another Number
Python open()
Python Program to Get a Substring of a String
Python Program to Illustrate Different Set Operations