从装饰器访问自我


79

在unittest的setUp()方法中,我设置了一些变量,稍后将在实际测试中引用它们。我还创建了一个装饰器来进行一些日志记录。有没有一种方法可以从装饰器访问这些变量?

为了简单起见,我将发布此代码:

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

什么是访问的最好办法一个从装饰(()在设置中设定)?

Answers:


120

由于您正在装饰一个方法,并且self是一个方法参数,因此装饰器可以self在运行时访问。显然不是在解析时,因为还没有对象,只有一个类。

因此,您将装饰器更改为:

def decorator(func):
    def _decorator(self, *args, **kwargs):
        # access a from TestSample
        print 'self is %s' % self
        return func(self, *args, **kwargs)
    return _decorator
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.