0
class A:
  def __init__(self):
    pass

class B(A):
  pass

class C(A):
  def __init__(self):
    pass

print(hasattr(B, '__init__')) # True
print(hasattr(C, '__init__')) # True

How to check if derived class has its own __init__ defined in Python? In the code above, only C has an __init__ definition, but B also has an __init__ attribute by inheritance. Is there a way to distinguish them?

csehydrogen
  • 374
  • 5
  • 17
  • 2
    What's a practical use case where that's important? – deceze Oct 19 '21 at 09:49
  • Does this answer your question? [Check if an instance has overridden a superclass method or not in Python](https://stackoverflow.com/questions/44913773/check-if-an-instance-has-overridden-a-superclass-method-or-not-in-python) – Tomerikoo Oct 19 '21 at 10:29

2 Answers2

2

You could just compare the two:

B.__init__==A.__init__
True
C.__init__==A.__init__
False
Kevin Müller
  • 722
  • 6
  • 18
2

You can use the __dict__ of a class

class A:
  def __init__(self):
    pass

class B(A):
  pass

class C(A):
  def __init__(self):
    pass

print(C.__dict__.__contains__('__init__'))
print(B.__dict__.__contains__('__init__'))

This also works and looks cleaner.

print('__init__' in C.__dict__)
print('__init__' in B.__dict__)

Even more cleaner

print('__init__' in vars(C))
print('__init__' in vars(B))

Gives output

True
False
Balaji
  • 795
  • 1
  • 2
  • 10
  • You can get the `__dict__` using the [`vars()`](https://docs.python.org/3/library/functions.html#vars) function. A bit cleaner and less "hacky" – Tomerikoo Oct 19 '21 at 10:32