How do I check if an object has an attribute?
You can use the hasattr
function to check if an object has an attribute. For example:
class MyClass:
def __init__(self):
self.attr = 1
obj = MyClass()
if hasattr(obj, 'attr'):
print('obj has attribute attr')
else:
print('obj does not have attribute attr')
This will print "obj has attribute attr".
You can also use the getattr
function to retrieve the value of an attribute, if it exists, or a default value if it does not. For example:
value = getattr(obj, 'attr', 0)
print(value) # prints 1
value = getattr(obj, 'other_attr', 0)
print(value) # prints 0
This can be useful if you want to retrieve the value of an attribute but you are not sure if the attribute exists or not.