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 Delete an Element From a Dictionary
Python repr()
Python String casefold()
Python Program to Convert Decimal to Binary Using Recursion
Python String isnumeric()
Python Program to Create Pyramid Patterns
Python Set intersection_update()
Python len()
Python Program to Extract Extension From the File Name
Python strftime()
Python slice()
Python Program to Print the Fibonacci sequence
Python print()
Python Program to Solve Quadratic Equation
Python Program to Get the Full Path of the Current Working Directory
Python List insert()
Python String isupper()
Python File I/O Operation
Python String format()
Python Dictionary pop()
Python Dictionary update()
Python Data Types
Python String split()
Python Numbers, Type Conversion and Mathematics
Python int()
Python filter()
Python Program to Concatenate Two Lists
Python Program to Illustrate Different Set Operations
Python String endswith()
Python Program to Display the multiplication Table
Deep Learning in Python - LazyProgrammer
Python divmod()