I want to have some functions that are called whenever a method of my object is called. These functions aren't defined by the method - they are given to the method later on (or may not be given at all). Is there a more elegant placeholder solution than using:

class MyObj:
    def __init__(self):
        self.bind = self.donothing #variable that may or may not be set by the parent

    def func(self):
        """Function to be called by the parent"""
        self.bind()

        ## do stuff

    @staticmethod
    def donothing():
        pass

1 Answers

1
Community On

You can do something like:

class MyObj:
    def __init__(self):
        self.bind = None

    def func(self):
        """Function to be called by the parent"""
        if self.bind:
            self.bind()

            ## do stuff

    def define_function(self, f):
        self.bind = f

Functions, like other objects, can be used as parameters to methods. Just initialize your variable without a value and assign one to it using a setter.