如何在python中为对象覆盖函数

问题描述

我在 python 2.7 中有一个项目。 用户会给我一个函数实现,我将用用户的实现覆盖我的基类函数。会有很多用户

class Base():

    def my_fun(self,x,y,z):
        ## to be overriden by user's function

from user_defined import user_function

base = Base()
base.my_fun = user_function

我是 python 的新手,如何在 python 中实现类似虚函数的东西,或者实现这一点的最佳方法是什么。同样要覆盖该功能,我将不得不导入用户定义其功能的所有文件。这如何在 for 循环中完成?

解决方法

方法与实例绑定的一些方法,选择一种,循环函数,绑定。

base.my_fun = user_function.__get__(base)

第二种方式:

import types
base.my_fun = types.MethodType(user_function,base)

第三种方式:

from functools import partial
base.my_fun = partial(user_function,base)

最后一种方式:

def bind(instance,method):
    def binding_scope_fn(*args,**kwargs):
        return method(instance,*args,**kwargs)
    return binding_scope_fn

base.my_fun = bind(base,user_function)