In Python, the hasattr()
function checks if a given object has a specified attribute.
hasattr(object, name)
object
: This represents the specified object that needs to be checked.
attribute
: This is the name of the attribute to be searched.
The hasattr()
function returns True
if a given object has the specified attribute. Otherwise, it returns False
.
The following code shows how to use the hasattr()
function in Python:
# Create the Animal class class Animal: name = 'Dog' color = 'brown' breed = 'Dachsador' # Create an instance of the Animal class animal = Animal() print('Does Animal has name?:', hasattr(animal, 'name')) print('Does it has an age?:', hasattr(animal, 'age')) print('Does it has a breed?:', hasattr(animal, 'breed'))
Lines 2–5: We create a class named Animal
which has the attributes name
, color
, and breed
.
Line 7: We create an instance of the Animal
class to access its attributes.
Lines 9–11: We use the hasattr()
function to check if the given object has the specified attribute. Finally, we display the result.
RELATED TAGS
CONTRIBUTOR
View all Courses