相关疑难解决方法(0)

实例方法的Python装饰器可以访问该类吗?

嗨我有类似下面的东西.基本上我需要从定义中的实例方法使用的装饰器访问实例方法的类.

def decorator(view):
    # do something that requires view's class
    print view.im_class
    return view

class ModelA(object):
    @decorator
    def a_method(self):
        # do some stuff
        pass
Run Code Online (Sandbox Code Playgroud)

代码原样给出

AttributeError: 'function' object has no attribute 'im_class'

我发现类似的问题/答案 - Python装饰器让函数忘记它属于一个类Python装饰器中的Get类 - 但这些依赖于一种解决方法,它通过抢夺第一个参数在运行时抓取实例.在我的情况下,我将基于从其类中收集的信息调用该方法,因此我不能等待来电.

谢谢.

python decorator

99
推荐指数
6
解决办法
5万
查看次数

使用与函数和方法相同的装饰器(带参数)

我一直在尝试创建一个可以在python中与函数和方法一起使用的装饰器.它本身就不那么难,但是当创建一个带参数的装饰器时,它似乎就是这样.

class methods(object):
    def __init__(self, *_methods):
        self.methods = _methods

    def __call__(self, func): 
        def inner(request, *args, **kwargs):
            print request
            return func(request, *args, **kwargs)
        return inner

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        new_func = self.func.__get__(obj, type)
        return self.__class__(new_func)
Run Code Online (Sandbox Code Playgroud)

上面的代码正确地包装了函数/方法,但是在方法的情况下,request参数是它正在操作的实例,而不是第一个非自身参数.

有没有办法判断装饰器是否应用于函数而不是方法,并相应地处理?

python methods arguments function decorator

14
推荐指数
3
解决办法
4431
查看次数

标签 统计

decorator ×2

python ×2

arguments ×1

function ×1

methods ×1