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 Global Keyword
Python slice()
Python String istitle()
Python Directory and Files Management
Python filter()
Python Program to Get the Last Element of the List
Python Program to Print Output Without a Newline
Python format()
Python Input, Output and Import
Python Program to Concatenate Two Lists
Python Program to Split a List Into Evenly Sized Chunks
Python strptime()
Python Program to Access Index of a List Using for Loop
Python Anonymous / Lambda Function
Python all()
Python bin()
Python Program to Count the Occurrence of an Item in a List
Python Program to Trim Whitespace From a String
Python Set copy()
Python set()
Python Object Oriented Programming
Python Program to Get the File Name From the File Path
Python Program to Append to a File
Python List append()
Python Program to Parse a String to a Float or Int
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python sum()
Learning scikit-learn Machine Learning in Python - Raul Garreta & Guillermo Moncecchi
Python Program to Check Prime Number
Python bytes()
Python String format()
Python time Module