Search code examples
pythonclassinheritancebuilt-in

Inheritance Method in Python


Is there a method in python that will trigger when class was inherited?

class Base:
  __inherit__( cls ):
    cls.bar += 'World!'

class Foo( Base ):
  bar = 'Hello, '

Foo.bar # 'Hello, World!'

Solution

  • I believe you are looking for __init_subclass__:

    class Base:
    
        def __init_subclass__(cls, **kwargs):
            cls.bar += "World"
    
    class Foo(Base):
        bar = 'Hello, '
    
    print(Foo.bar)
    

    Output:

    Hello, World