Explore Courses Blog Tutorials Interview Questions
+2 votes
in Python by (3.5k points)
edited by

How can I know if an object has some attribute in Python, Is there a way to do it?


    >>> q = SomeClass()
    >>> q.someProperty = value
    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

2 Answers

0 votes
by (2k points)
edited by

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.

Happy Learning. 

0 votes
by (106k points)

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:-

Related questions

0 votes
1 answer
asked Apr 5, 2020 in BI by Vaibhav Ameta (17.6k points)
+2 votes
3 answers
asked May 24, 2019 in Python by Suresh (3.4k points)
+3 votes
2 answers
asked May 28, 2019 in Python by Ritik (3.5k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories