Back
How can I know if an object has some attribute in Python, Is there a way to do it?
E.g.
>>> 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?
Learn more about Python from an expert. Enroll in our Python Course
These is a very easy task to do, just try hasattr() :
if hasattr(q, 'property'): q.property
This Is a very fast and elegant method and will solve your problem.
Happy Learning.
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:-
31k questions
32.8k answers
501 comments
693 users