Home > Software design >  How to check if a derived class has its own __init__ defined in Python?
How to check if a derived class has its own __init__ defined in Python?

Time:10-19

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?

CodePudding user response:

You could just compare the two:

B.__init__==A.__init__
True
C.__init__==A.__init__
False

CodePudding user response:

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
  • Related