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 Compute the Power of a Number
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Variables, Constants and Literals
Python String count()
Python String isalpha()
Python String isupper()
Python Program to Find Sum of Natural Numbers Using Recursion
Python Program to Extract Extension From the File Name
Python Recursion
Python String istitle()
Python hash()
Python tuple()
Python String isdecimal()
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Function Arguments
Python Program to Find the Sum of Natural Numbers
Python print()
Python open()
Python Namespace and Scope
Python Program to Print the Fibonacci sequence
Python help()
Python staticmethod()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Illustrate Different Set Operations
Python List clear()
Python Program to Convert Celsius To Fahrenheit
Python String capitalize()
Python Iterators
Python Program to Find the Square Root
Python reversed()
Python classmethod()