Thursday, 25 March 2021

How to enforce mandatory parent method call when calling child method?

What I want is to enforce that when a child class inherits from a parent and that it overrides the parent method without explicitly calling it, an error is raised. The errror could be raised at initialization of the bad class or when calling the method.

The goal is to make sure that users of the Mother class performed some actions present in the mother method.

Example

class Mother():
    def necessary_method(self):
         # do some necessary stuff

class GoodChild(Mother):
    def necessary_method(self):
        # necessary parent call
        super().necessary_method()

class BadChild(Mother):
    def necessary_method(self):
         # no parent call
         return

upon calling:

good = GoodChild()
# works fine
bad = BadChild()
# exception could be raised here

good.necessary_method()
# works fine
bad.necessary_method()
# exception could be raised here

Is this really possible ? Any answer or workaround tricks is welcomed.



from How to enforce mandatory parent method call when calling child method?

No comments:

Post a Comment