Dynamically assigning function implementation in Python

感情迁移 提交于 2019-12-02 20:55:48
yak

Your first approach was OK, you just have to assign the function to the class:

class Doer(object):
    def __init__(self):
        self.name = "Bob"

    def doSomething(self):
        print "%s got it done" % self.name

def doItBetter(self):
    print "%s got it done better" % self.name

Doer.doSomething = doItBetter

Anonymous functions have nothing to do with this (by the way, Python supports simple anonymous functions consisting of single expressions, see lambda).

yak's answer works great if you want to change something for every instance of a class.

If you want to change the method only for a particular instance of the object, and not for the entire class, you'd need to use the MethodType type constructor to create a bound method:

from types import MethodType

doer.doSomething = MethodType(doItBetter, doer, Doer)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!