Home > Mobile >  Binding a method to class instance on fly in Python
Binding a method to class instance on fly in Python

Time:02-15

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


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

The above codes do not work: TypeError: myfunc() missing 1 required positional argument: 'self'. Why the instance name is not automatically inserted by python, considering the fact that the dot notation is used?

CodePudding user response:

It can work like this, since the function isn't really an instance method

class mc:
    def show(self):
         self.x = 1
         func(self)


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

CodePudding user response:

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()
  • Related