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 rsplit()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python dict()
Python Program to Swap Two Variables
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Set add()
Python Program to Copy a File
Python Generators
Python Program to Compute all the Permutation of the String
Python String format()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python sorted()
Python Functions
Python String swapcase()
Python int()
Python Program to Remove Duplicate Element From a List
Python Program to Represent enum
Python String casefold()
Python Program to Find the Sum of Natural Numbers
Python Program to Iterate Through Two Lists in Parallel
Python type()
Python Iterators
Python Program to Add Two Matrices
Python any()
Python Program to Multiply Two Matrices
Python callable()
Python set()
Python Program to Illustrate Different Set Operations
Python delattr()
Python frozenset()
Python Program to Merge Mails
Python Program to Check Armstrong Number