且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将功能分配给对象属性

更新时间:2023-02-09 14:23:29

操作方法如下:

import types
class Scriptable:
    def __init__(self, script = None):
        if script is not None:
            self.script = types.MethodType(script, self)   # replace the method
    def script(self):
        print("greetings from the default script")

正如评论中的ba__friend所述,方法存储在class对象上.当您从实例访问属性时,类对象上的描述符将函数作为绑定方法返回.

As ba__friend noted in the comments, methods are stored on the class object. A descriptor on the class object returns functions as bound methods when you access the attribute from a instance.

当您将功能分配给instance时,不会发生任何特殊情况,因此您必须自己包装该功能.

When you assign a function to a instance nothing happens special happens, so you have to wrap the function yourself.