从装饰器访问 self

在 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

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

32202 次浏览

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