- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How I can check if class attribute was defined or derived in given class in Python?
The code below shows the if the attribute 'foo' was defined or derived in the classes A and B.
Example
class A: foo = 1 class B(A): pass print A.__dict__ #We see that the attribute foo is there in __dict__ of class A. So foo is defined in class A. print hasattr(A, 'foo') #We see that class A has the attribute but it is defined. print B.__dict__ #We see that the attribute foo is not there in __dict__ of class B. So foo is not defined in class B print hasattr(B, 'foo') #We see that class B has the attribute but it is derived
Output
{'__module__': '__main__', 'foo': 1, '__doc__': None} True {'__module__': '__main__', '__doc__': None} True
- Related Articles
- How do we check if a class is a subclass of the given super class in Python?
- How can I check if a JavaScript function is defined?
- How to use selenium to check if element contains specific class attribute?
- How to call a parent class function from derived class function in C++?
- How I can create Python class from JSON object?
- How to create an unordered_set of user defined class or struct in C++?
- Accessing protected members in a C++ derived class
- How can I check whether a variable is defined in JavaScript?
- How do I create static class data and static class methods in Python?
- HTML Class Attribute
- What does built-in class attribute __dict__ do in Python?
- What does built-in class attribute __doc__ do in Python?
- What does built-in class attribute __module__ do in Python?
- What does built-in class attribute __bases__ do in Python?
- Class or Static Variables in Python?

Advertisements