The Altruist
The Altruist

Reputation: 93

In Python2, how to force a child class method to call a parent method without explicitly requiring the end user to include it?

A parent class I'm writing requires some specific internal cleanup after usage. The child class has its own cleanup to do, but the parent's cleanup function must be run afterward. Obviously, a call to super would solve this, but I'd like this to be as simple as possible on the child class's side.

I tried decorating the parent method. This did not work.

# The parent class whose inner-workings I don't expect the end user to understand
class ParentClass(object):
    def __init__(self, *args, **kwargs):
        self._personal_message = "Parent class says:"
        self._important_message = "I'm important!"

    # The method that NEEDS to be run in all instances of ParentClass and its subclasses
    def _important_method(self):
        print(self._important_message)

    # The decorator I thought would work
    def _pretty_decoration(func):
        def func_wrapper(self):
            func_self = func(self)
            self._important_method()
            return func_self
        return func_wrapper

    # The decorated function that will be overridden by the child class
    @_pretty_decoration
    def do_something(self):
        print(self._personal_message)

    # Make the decorator static
    _pretty_decoration = staticmethod(_pretty_decoration)


# The blissfully naive Child class
class ChildClass(ParentClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)
        self._personal_message = "Child class says:"

    # The overriding method
    def do_something(self):
        print(self._personal_message)
        self.do_something_else()

    def do_something_else(self):
        print("I am blissfully naive.")


# The test drive
parent = ParentClass()
parent.do_something()
child = ChildClass()
child.do_something()

In this example, I'm getting:

Parent class says:
I'm important!
Child class says:
I am blissfully naive.

whereas I was hoping to get:

Parent class says:
I'm important!
Child class says:
I am blissfully naive.
I'm important!

What should I be doing for the expected result?

Upvotes: 1

Views: 95

Answers (1)

chepner
chepner

Reputation: 531155

Rather than override the method, defer the real work to a callback method called from do_something. Then there is no reason to override do_something, and you can just put the call to _important_method directly in its body.

class ParentClass(object):
    def __init__(self, *args, **kwargs):
        self._personal_message = "Parent class says:"
        self._important_message = "I'm important!"

    # The method that NEEDS to be run in all instances
    # of ParentClass and its subclasses
    def _important_method(self):
        print(self._important_message)

    # This doesn't get overriden; it's a fixed entry point to do_body
    def do_something(self):
        self.do_body()
        self._important_method()

    # This shouldn't (need to) be called directly
    def do_body(self):
        print(self._personal_message)


class ChildClass(ParentClass):
    def do_body(self):
        print(self._personal_message)  # or super().do_body()
        self.do_something_else()

    def do_something_else(self):
        print("I am blissfully naive.")

Then the following still works

child = ChildClass()
child.do_something()

Upvotes: 3

Related Questions