[SOLVED] Binding a method to class instance on fly in Python

Issue

class mc:
    def show(self):
        self.func()


a = mc()
def myfunc(self):
    print('instance function')
a.func = myfunc
a.show()

The above does not work: TypeError: myfunc() missing 1 required positional argument: 'self'.

Why is the instance name not automatically inserted by Python, considering that I’m using dot notation?

Solution

You can dynamically add a method to a class using monkey patching.

class mc:
    def show(self):
        self.func()

a = mc()
def myfunc(self):
    print('instance function')
mc.func = myfunc
a.show()

Answered By – BrokenBenchmark

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.