从装饰器访问 self [英] Access self from decorator

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

问题描述

在 unittest 的 setUp() 方法中,我设置了一些 self 变量,这些变量稍后会在实际测试中引用.我还创建了一个装饰器来做一些日志记录.有没有办法从装饰器访问那些 self 变量?

In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator?

为了简单起见,我发布了这段代码:

For the sake of simplicity, I'm posting this code:

def decorator(func):
    def _decorator(*args, **kwargs):
        # access a from TestSample
        func(*args, **kwargs)
    return _decorator

class TestSample(unittest.TestCase):    
    def setUp(self):
        self.a = 10

    def tearDown(self):
        # tear down code

    @decorator
    def test_a(self):
        # testing code goes here

从装饰器访问 a(在 setUp() 中设置)的最佳方式是什么?

What would be the best way of accessing a (set in setUp()) from decorator?

推荐答案

既然你在装饰一个方法,而 self 是一个方法参数,你的装饰器可以访问 self 在运行时.显然不是在解析时,因为还没有对象,只有一个类.

Since you're decorating a method, and self is a method argument, your decorator has access to self at runtime. Obviously not at parsetime, because there are no objects yet, just a class.

因此您将装饰器更改为:

So you change your decorator to:

def decorator(func):
    def _decorator(self, *args, **kwargs):
        # access a from TestSample
        print 'self is %s' % self
        return func(self, *args, **kwargs)
    return _decorator

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

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