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 memoryview()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python frozenset()
Python Program to Add Two Numbers
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Set add()
Python staticmethod()
Python Errors and Built-in Exceptions
Python String format()
Python Program to Find LCM
Python list()
Python divmod()
Python Dictionary popitem()
Python chr()
Python Program to Randomly Select an Element From the List
Deep Learning in Python - LazyProgrammer
APIs in Node.js vs Python - A Comparison
Python Program to Print all Prime Numbers in an Interval
Python List append()
Python Program to Make a Flattened List from Nested List
Python Program to Measure the Elapsed Time in Python
Python Deep Learning Cookbook - Indra den Bakker
Python any()
Python float()
Python String casefold()
Python Program to Find HCF or GCD
Python File I/O Operation
Python String splitlines()
Python Exception Handling Using try, except and finally statement
Python String lower()
Python Directory and Files Management
Python Operator Overloading