How can I know if an object has some attribute in Python, Is there a way to do it?
>>> q = SomeClass() >>> q.someProperty = value >>> q.property Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: SomeClass instance has no attribute 'property'
so, How can I know that q has the attribute property before using it in syntax?
These is a very easy task to do, just try hasattr() :
if hasattr(q, 'property'):
This Is a very fast and elegant method and will solve your problem.
You can use the getattr() function for knowing whether an object has attribute in Python or not:-
getattr(a, 'property', 'default value')
You can use the following video tutorials to clear all your doubts:-