hasattr() is one of Python's built-in functions, used to check whether an object has a specified attribute or method.
Function Syntax
hasattr(object, name)
Parameters:
object: The object to be checked.name: The name of the attribute or method to check, can be a string or identifier.
Returns True if the object has the specified attribute or method, otherwise returns False. This functionality is implemented by calling getattr(object, name) and checking if an AttributeError exception is raised.
Related reference:
hasattr() Function Examples
Check if an instance has a specific attribute or method:
class Person:
def __init__(self, name):
self.name = name
def say_hello(self):
print(f"Hello, my name is {self.name}.")
person = Person("Alice")
# Check if instance has attributes
print(hasattr(person, "name")) # True
print(hasattr(person, "age")) # False
if hasattr(person, "say_hello"):
person.say_hello()