How to get self into a Python method without explicitly accepting it

后端 未结 5 1006
失恋的感觉
失恋的感觉 2020-12-09 12:53

I\'m developing a documentation testing framework -- basically unit tests for PDFs. Tests are (decorated) methods of instances of classes defined by the framework, and these

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 13:34

    little upgrade for aaronasterling's solution( i haven't enough reputation to comment it ):

    def wrap(f):
        @functools.wraps(f)
        def wrapper(self,*arg,**kw):
            f.func_globals['self'] = self        
            return f(*arg,**kw)
        return wrapper
    

    but both this solutions will work unpredictable if f function will be called recursively for different instance, so you have to clone it like this:

    import types
    class wrap(object):
        def __init__(self,func):
            self.func = func
        def __get__(self,obj,type):
            new_globals = self.func.func_globals.copy()
            new_globals['self'] = obj
            return types.FunctionType(self.func.func_code,new_globals)
    class C(object):
        def __init__(self,word):
            self.greeting = word
        @wrap
        def greet(name):
            print(self.greeting+' , ' + name+ '!')
    C('Hello').greet('kindall')
    

提交回复
热议问题