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 Set intersection()
Python Program to Randomly Select an Element From the List
Python Set intersection_update()
How to Get Started With Python?
Python Program to Check if a Number is Odd or Even
Python String isdecimal()
Python Program to Check If Two Strings are Anagram
Python float()
Python Get Current time
Python String translate()
Python *args and **kwargs
Python Numbers, Type Conversion and Mathematics
Python Program to Copy a File
Python property()
Python Global, Local and Nonlocal variables
Python Program to Solve Quadratic Equation
Python map()
Python Program to Represent enum
Python Generators
Python File I/O Operation
Python Program to Trim Whitespace From a String
Python repr()
Python Program to Append to a File
Python Program to Check the File Size
Python @property decorator
Python frozenset()
Python Program to Add Two Matrices
Python Program to Split a List Into Evenly Sized Chunks
Python Decorators
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python min()
Python break and continue