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 Print Hello world!
Python String rfind()
Python List count()
Python pow()
Python Dictionary
Python List copy()
Python Program to Capitalize the First Character of a String
Python String isdigit()
Python String splitlines()
Python Functions
Python strptime()
Python for Loop
Python sleep()
Python Program to Differentiate Between type() and isinstance()
Python Closures
How to Get Started With Python?
Python int()
Python Operators
Python Package
Python Program to Count the Number of Occurrence of a Character in String
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Program to Check Leap Year
Python Multiple Inheritance
Python Program to Check Whether a String is Palindrome or Not
Python Program to Create a Long Multiline String
Python Object Oriented Programming
Python Program to Safely Create a Nested Directory
Python Dictionary popitem()
Python Program to Check if a Key is Already Present in a Dictionary
Python List pop()
Python Program to Check If a String Is a Number (Float)
Python bytearray()