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 Add Two Numbers
Python Program to Get the Last Element of the List
Python Dictionary
Python sleep()
Python Program to Convert Bytes to a String
Python globals()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python String replace()
Python locals()
Python Program to Find Armstrong Number in an Interval
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Count the Occurrence of an Item in a List
Python bytearray()
Python Program to Reverse a Number
Python dir()
Python Program to Make a Simple Calculator
Python String isupper()
Python Set difference()
Python help()
Python Function Arguments
Python Program to Find LCM
Python Set symmetric_difference_update()
Python String lstrip()
Python String join()
Python Program to Solve Quadratic Equation
Python Program to Iterate Through Two Lists in Parallel
Python Program to Find the Factors of a Number
Python Program to Find Hash of File
Python @property decorator
Python Program to Create Pyramid Patterns
Python issubclass()
Python Program to Safely Create a Nested Directory