Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
148 views
in Technique[技术] by (71.8m points)

How to override function in python for objects

I have a project in python 2.7. The user will give me a function implementation and I will override my base class function with the user's implementation. There will be many users.

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

I am new to python, how to implement something like virtual function in python, or what is the best way to accomplish this. Also to override that function I will have to import all the files in which the user has defined their function. How can this be done inside a for loop?

question from:https://stackoverflow.com/questions/66058344/how-to-override-function-in-python-for-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some ways for binding method with instance, chose one, and loop the functions, and bind them.

base.my_fun = user_function.__get__(base)

2nd way:

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

3rd way:

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

last way:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...