Python decorator as a staticmethod

前端 未结 4 1720
天涯浪人
天涯浪人 2020-11-28 10:42

I\'m trying to write a python class which uses a decorator function that needs information of the instance state. This is working as intended, but if I explicitly make the d

4条回答
  •  再見小時候
    2020-11-28 10:54

    Solution does exist!

    Problem is that Static method that is trying to be used as decorator is in fact staticmethod object and is not callable.

    Solution: staticmethod object has method __get__ which takes any argument and returns real method: python documentation Python 3.5 and up:

    class StaticMethod(object):
        "Emulate PyStaticMethod_Type() in Objects/funcobject.c"
    
        def __init__(self, f):
            self.f = f
    
        def __get__(self, obj, objtype=None):
            return self.f
    

    Min solution I came with is:

    class A():
        def __init__(self):
            self.n =  2
    
        @staticmethod
        def _returnBaseAndResult(func):
            from functools import wraps
            @wraps(func)
            def wrapper(*args, **kwargs):
                self = args[0]
                response = func(*args, **kwargs)
                return self.n, response
            return wrapper
    
        @_returnBaseAndResult.__get__('this can be anything')
        def square(self):
            return self.n**2
    
    if __name__ == '__main__':
        a = A()
        print(a.square())
    

    Will print (2, 4)

提交回复
热议问题