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 Illustrate Different Set Operations
Python Directory and Files Management
Python List sort()
Python Program to Add Two Matrices
Python Program to Find Sum of Natural Numbers Using Recursion
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python id()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Convert String to Datetime
Python Program to Find HCF or GCD
Python Functions
Python Program to Check If a String Is a Number (Float)
Python String rsplit()
Python Tuple count()
Python callable()
Python File I/O Operation
Python frozenset()
APIs in Node.js vs Python - A Comparison
Python String rpartition()
Python Object Oriented Programming
Python String expandtabs()
Python Program to Append to a File
Python Set clear()
Python Program to Merge Two Dictionaries
Python Program to Check If Two Strings are Anagram
Python Program to Trim Whitespace From a String
Python Program to Count the Number of Digits Present In a Number
Python Statement, Indentation and Comments
Python float()
Python Program to Check if a Key is Already Present in a Dictionary
Python hex()
Python Program to Display Powers of 2 Using Anonymous Function