类中的Python装饰器 [英] Python decorators in classes

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

问题描述

可以这样写:

class Test(object):
    def _decorator(self, foo):
        foo()

    @self._decorator
    def bar(self):
        pass

这失败:self in @self is unknown

This fails: self in @self is unknown

我也试过:

@Test._decorator(self)

也失败:测试未知

如果想要temp。在
改变它们之前,在装饰器中更改一些实例变量
并运行修饰的方法。

If would like to temp. change some instance variables in the decorator and the run the decorated method, before changing them back.

谢谢。

推荐答案

你想要做的是不可能的。例如,下面的代码是否看起来有效:

What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:

class Test(object):

    def _decorator(self, foo):
        foo()

    def bar(self):
        pass
    bar = self._decorator(bar)

当然,因为 self 没有在那一点定义。对于 Test 也是如此,因为它不会被定义,直到类本身被定义(它在其过程中)。我会向您显示此代码段,因为这是装饰器代码段转换为

It, of course, isn't valid since self isn't defined at that point. The same goes for Test as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because this is what your decorator snippet transforms into.

因此,如您所见,访问实例在这样的装饰器是不是真的可能,因为装饰器是应用于任何函数/方法,它们附加到而不是实例化。

So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.

如果你需要类级访问,请尝试:

class Test(object):

    @classmethod
    def _decorator(cls, foo):
        foo()

    def bar(self):
        pass
Test.bar = Test._decorator(Test.bar)

这篇关于类中的Python装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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