A useful built in function in Python is hasattr(). This function is used to test if an object has some attribute. hasattr() returns True if the object you specify contains a particular attribute and False if it does not.
hasattr() syntax:
[sourcecode lang=”python”]
hasattr(object, attribute)
[/sourcecode]
hasattr() takes two parameters:
- object. The object whose attribute you want to check
- attribute. A string that contains the name of the attribute you’re searching for
The code example below shows how to use hasattr().
[sourcecode lang=”python”]
class Event:
    def __init__(self, name, location):
        self.name = name
        self.location = location
wedding = Event("Vuyisile’s Wedding", "Madagascar")
hasattr(wedding, "name")
[/sourcecode]
In the example above, hasattr() would return True since the Event class has a “name” attribute. To get the value of the attribute, use getattr():
[code lang=python]
>>> getattr(wedding, "location")
"Madagascar"
[/code]