Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...