10.6. Reflection Hasattr
Check if object has attribute
There is no
__hasattr__()methodCalling
hasattr(obj, attrname)Will call
__getattribute__()and checks if raisesAttributeErrorIf no exception, then return
TrueIf exception, then call
__getattr__()and checkIf
__getattr__()succeeds then returnTrueIf
__getattr__()fail then returnFalse
10.6.1. Example
>>> class Point:
... x: int
... y: int
... z: int
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> hasattr(pt, 'x')
True
>>>
>>> hasattr(pt, 'y')
True
>>>
>>> hasattr(pt, 'z')
False
>>>
>>> hasattr(pt, 'other')
False