实例方法的装饰器可以访问该类吗? [英] Can a decorator of an instance method access the class?

查看:67
本文介绍了实例方法的装饰器可以访问该类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大概有以下内容。基本上,我需要从定义该实例方法的装饰器中访问该实例方法的类。

I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition.

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

代码按原样给出:


AttributeError:函数对象没有属性 im_class

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

我发现了类似的问题/答案- Python装饰器使函数忘记了它属于一个类在Python装饰器中获取类-但是这些方法依赖于一种解决方法,该解决方法通过在运行时抓取第一个参数来获取实例。就我而言,我将基于从其类中收集的信息来调用该方法,因此我等不及调用了。

I found similar question/answers - Python decorator makes function forget that it belongs to a class and Get class in Python decorator - but these rely upon a workaround that grabs the instance at run-time by snatching the first parameter. In my case, I will be calling the method based upon the information gleaned from its class, so I can't wait for a call to come in.

推荐答案

如果您使用的是Python 2.6或更高版本,则可以使用类装饰器,也许是这样的东西(警告:未经测试的代码)。

If you are using Python 2.6 or later you could use a class decorator, perhaps something like this (warning: untested code).

def class_decorator(cls):
   for name, method in cls.__dict__.iteritems():
        if hasattr(method, "use_class"):
            # do something with the method and class
            print name, cls
   return cls

def method_decorator(view):
    # mark the method as something that requires view's class
    view.use_class = True
    return view

@class_decorator
class ModelA(object):
    @method_decorator
    def a_method(self):
        # do some stuff
        pass

方法装饰器将方法标记为通过添加 use_class而引起关注属性-函数和方法也是对象,因此您可以将其他元数据附加到它们。

The method decorator marks the method as one that is of interest by adding a "use_class" attribute - functions and methods are also objects, so you can attach additional metadata to them.

在创建了类之后,类装饰器将遍历所有方法并执行

After the class has been created the class decorator then goes through all the methods and does whatever is needed on the methods that have been marked.

如果希望影响所有方法,则可以省去方法装饰器,而只需使用类装饰器。

If you want all the methods to be affected then you could leave out the method decorator and just use the class decorator.

这篇关于实例方法的装饰器可以访问该类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆