If I had a dictionary dict
and I wanted to check for dict['key']
I could either do so in a try
block (bleh!) or use the get()
method, with False
as a default value.
I'd like to do the same thing for object.attribute
. That is, I already have object to return False
if it hasn't been set, but then that gives me errors like
AttributeError: 'bool' object has no attribute 'attribute'
We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.
A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.
Accessing the attributes of a classgetattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class. setattr() − A python method used to set an additional attribute in a class.
Python class attributes are variables of a class that are shared between all of its instances. They differ from instance attributes in that instance attributes are owned by one specific instance of the class only, and are not shared between instances.
A more direct analogue to dict.get(key, default)
than hasattr
is getattr
.
val = getattr(obj, 'attr_to_check', default_value)
(Where default_value
is optional, raising an exception on no attribute if not found.)
For your example, you would pass False
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With