The hasattr()
function in Python is a built-in function that returns True if the specified object has the given attribute, and False if not. It takes two parameters: an object and a string representing the attribute name. This function is commonly used to check if an object has a particular attribute before trying to access it.
Parameter Values
Parameter | Description |
---|---|
object | The |
name | A |
Return Values
The hasattr()
function returns a bool
, either True
or False
.
How to Use hasattr()
in Python
The hasattr()
function in Python is used to determine if an object has the specified attribute.
class Person:
name = 'Alice'
age = 30
print(hasattr(Person, 'name')) # Output: True
print(hasattr(Person, 'gender')) # Output: False
It returns True
if the object has the given attribute, else it returns False
.
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
car = Vehicle('Toyota', 'Corolla')
print(hasattr(car, 'make')) # Output: True
print(hasattr(car, 'color')) # Output: False
The hasattr()
function can also be used to check if the object has a specific method.
class Calculator:
def add(self, x, y):
return x + y
calc = Calculator()
print(hasattr(calc, 'add')) # Output: True
print(hasattr(calc, 'subtract')) # Output: False