How to run code when a class is subclassed?

StackOverflow

Is there a way to trigger code when my class is subclassed?

class SuperClass:
    def triggered_routine(subclass):
        print("was subclassed by " + subclass.__name__)

magically_register_triggered_routine()

print("foo")

class SubClass0(SuperClass):
    pass

print("bar")

class SubClass1(SuperClass):
    print("test")

Should output

foo
was subclassed by SubClass0
bar
test
was subclassed by SubClass1




Get Solution for free from DataCamp guru