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 String expandtabs()
Python String rpartition()
Python Modules
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python Sets
Python __import__()
Python frozenset()
Python Program to Swap Two Variables
Node.js vs Python for Backend Development
Python Program to Find the Square Root
Python Program to Find ASCII Value of Character
Python Deep Learning Cookbook - Indra den Bakker
Python String rindex()
Python while Loop
Python Program to Find Sum of Natural Numbers Using Recursion
Python Keywords and Identifiers
Python Package
Python Program to Get the Class Name of an Instance
Python Program to Check Whether a String is Palindrome or Not
Python Global Keyword
Python Program to Print the Fibonacci sequence
Python locals()
Python Program to Sort a Dictionary by Value
Intelligent Projects Using Python - Santanu Pattanayak
Python Dictionary popitem()
Python Objects and Classes
Python ord()
Python isinstance()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Program to Find the Factors of a Number
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Print Colored Text to the Terminal