Python built-in Method - hasattr()
The hasattr() method in Python is a built-in function that returns a Boolean value indicating whether an object has a given attribute or not.
The syntax for hasattr() is as follows:
hasattr(object, name)
Here, object is the object to be checked for the attribute, and name is the name of the attribute.
For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 30)
has_name = hasattr(person, "name")
print(has_name) # Output: True
has_salary = hasattr(person, "salary")
print(has_salary) # Output: False
In the example above, we define a Person class with two attributes name and age. We create an instance of the class called person. We use hasattr() to check if person has a name attribute, which it does. We then print the Boolean value True.
We also use hasattr() to check if person has a salary attribute, which it does not. We then print the Boolean value False.
hasattr() is useful when you want to check if an object has a particular attribute before trying to access it. This can be especially useful when working with objects whose attributes are not known ahead of time or are generated at runtime.
