English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
If the object has the given named attribute, the hasattr() method returns true, otherwise it returns false.
The syntax of the hasattr() method is:
hasattr(object, name)
The hasattr() method is called by getattr() to check whether AttributeError is raised.
The hasattr() method takes two parameters:
object -The object to check for named attributes
name -The name of the property to search for
The hasattr() method returns:
TrueIf the object has the given defined attribute
FalseIf the object does not have the given defined attribute
class Person: age = 23 name = 'Adam' person = Person() print('Person has an age attribute?:', hasattr(person, 'age')) print('Person has a salary attribute?:', hasattr(person, 'salary'))
When running the program, the output is:
Person has an age attribute?: True Person has a salary attribute?: False