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 Global, Local and Nonlocal variables
Node.js vs Python for Backend Development
Python Program Read a File Line by Line Into a List
Python Global Keyword
Python Dictionary items()
Python Program to Convert Kilometers to Miles
Python String rfind()
Python Set copy()
Python Program to Make a Simple Calculator
Python next()
Python filter()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Anonymous / Lambda Function
Python Program to Parse a String to a Float or Int
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Sort Words in Alphabetic Order
Python delattr()
Python Namespace and Scope
Python Dictionary fromkeys()
Python while Loop
Python Inheritance
Python RegEx
Python Set clear()
Python Operator Overloading
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python Set discard()
Python format()
Python __import__()
Python String maketrans()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Check If a List is Empty
Python Program to Find Armstrong Number in an Interval