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 len()
Python Program to Generate a Random Number
Python time Module
Python Dictionary update()
Python String lstrip()
Python String startswith()
Python Program to Capitalize the First Character of a String
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Convert Celsius To Fahrenheit
Python *args and **kwargs
Python Dictionary popitem()
Python String expandtabs()
Python Program to Represent enum
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python list()
Python iter()
Python Dictionary copy()
Python String format_map()
Python Program to Find the Factorial of a Number
Python Program to Print Hello world!
Python String isprintable()
Python Program to Shuffle Deck of Cards
Python locals()
Python String rstrip()
Python Program to Display the multiplication Table
Python Tuple count()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Check if a Number is Positive, Negative or 0
Python Keywords and Identifiers
Python sum()
Python Decorators
Python sorted()