class mc:
def show(self):
self.func()
a = mc()
def myfunc(self):
print('instance function')
a.func = myfunc
a.show()
上面的方法不起作用:TypeError: myfunc() 缺少 1 个必需的位置参数:'self'
。
考虑到我使用的是点表示法,为什么 Python 没有自动插入实例名称?
最佳答案
您可以使用 monkey patching 向类动态添加方法.
class mc:
def show(self):
self.func()
a = mc()
def myfunc(self):
print('instance function')
mc.func = myfunc
a.show()
关于python - 在 Python 中将方法动态绑定(bind)到类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71121996/