Python 3 reference · Built-in Functions
Python hasattr() Function
Return True if an object has an attribute with the given name. It works by calling getattr() and catching AttributeError.
Python 3 Since 3.0
Syntax
hasattr(object, name)
Parameters
| Parameter | Description |
|---|---|
object |
Any object. |
name |
The attribute name as a string. |
Return value
True or False.
Examples
print(hasattr("text", "upper"))
print(hasattr([1, 2], "upper"))
Output
True False
class Duck:
def quack(self): return "Quack!"
class Robot:
pass
for thing in [Duck(), Robot()]:
print(thing.quack() if hasattr(thing, "quack") else "can't quack")
Output
Quack! can't quack
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
getattr()· Get an attribute by name, given as a string. An optional default is returned instead of raising AttributeError.setattr()· Set an attribute on an object by name, given as a string. setattr(obj, 'x', 5) is the same as obj.x = 5.delattr()· Delete a named attribute from an object. delattr(obj, 'name') does the same as del obj.name when the name is in a variable.callable()· Return True if an object can be called like a function: functions, classes, methods and objects with __call__().- Python Classes and Objects · tutorial