Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
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?

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?

2 Answers

0 votes
by (2k points)
edited by

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. 

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!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...