从装饰器访问自身

问题描述 投票:67回答:2

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

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

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()中设置)的最佳方法是什么?

python unit-testing scope
2个回答
103
投票

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

所以您将装饰器更改为:

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

0
投票

Dave提出的建议甚至在同一个班级的装饰员中也起作用。谢谢戴夫

© www.soinside.com 2019 - 2024. All rights reserved.