Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How I can check if class attribute was defined or derived in given class in Python?
In Python, you can check if a class attribute was defined directly in a class or inherited from a parent class by examining the class's __dict__ attribute and using hasattr().
Understanding Class Attributes
When a class inherits from another class, it can access parent class attributes. To distinguish between defined and inherited attributes, check if the attribute exists in the class's own __dict__.
Example
Let's create two classes to demonstrate defined vs inherited attributes ?
class A:
foo = 1
class B(A):
pass
# Check if 'foo' is defined in class A
print("Class A __dict__:", A.__dict__)
print("Class A has 'foo':", hasattr(A, 'foo'))
print("'foo' defined in A:", 'foo' in A.__dict__)
print()
# Check if 'foo' is defined in class B
print("Class B __dict__:", B.__dict__)
print("Class B has 'foo':", hasattr(B, 'foo'))
print("'foo' defined in B:", 'foo' in B.__dict__)
The output shows the difference between defined and inherited attributes ?
Class A __dict__: {'__module__': '__main__', 'foo': 1, '__qualname__': 'A'}
Class A has 'foo': True
'foo' defined in A: True
Class B __dict__: {'__module__': '__main__', '__qualname__': 'B'}
Class B has 'foo': True
'foo' defined in B: False
Key Differences
| Method | Purpose | Result for A.foo | Result for B.foo |
|---|---|---|---|
hasattr() |
Check if attribute exists (defined or inherited) | True | True |
in __dict__ |
Check if attribute is defined in this class | True | False |
Practical Function
Here's a utility function to check attribute origin ?
def check_attribute_origin(cls, attr_name):
if hasattr(cls, attr_name):
if attr_name in cls.__dict__:
return f"'{attr_name}' is defined in {cls.__name__}"
else:
return f"'{attr_name}' is inherited in {cls.__name__}"
else:
return f"'{attr_name}' not found in {cls.__name__}"
class A:
foo = 1
class B(A):
bar = 2
# Test the function
print(check_attribute_origin(A, 'foo'))
print(check_attribute_origin(B, 'foo'))
print(check_attribute_origin(B, 'bar'))
print(check_attribute_origin(B, 'xyz'))
'foo' is defined in A 'foo' is inherited in B 'bar' is defined in B 'xyz' not found in B
Conclusion
Use hasattr() to check if an attribute exists anywhere in the inheritance chain. Use attr_name in cls.__dict__ to check if an attribute is defined specifically in that class, not inherited.
