2
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?

1
  • 1
    If you want to make an instance method, just make it an instance method in the regular way. However for your myfunc I would expect it to be a regular function that you are just storing as the func attrbute of a particuar instance of mc. Commented Feb 15, 2022 at 6:38

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.