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 rpartition()
Python List pop()
Python Program to Check Leap Year
Python len()
Python String partition()
Python del Statement
Python String rstrip()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Check Whether a String is Palindrome or Not
Python String istitle()
Python String startswith()
Python Program to Create a Long Multiline String
Python Program to Split a List Into Evenly Sized Chunks
Python Program to Make a Simple Calculator
Python Statement, Indentation and Comments
Python all()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python iter()
Python Program to Add Two Numbers
Python super()
Python Package
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python str()
Python Set intersection_update()
Python Dictionary pop()
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Python String rindex()
Python Set pop()
Python Object Oriented Programming
Python Program to Convert Celsius To Fahrenheit
Python Program to Compute the Power of a Number
Python Set difference_update()