我将装饰器 @login_testuser
应用于方法 test_1()
:
class TestCase(object):
@login_testuser
def test_1(self):
print "test_1()"
有没有一种方法可以将 @login_testuser
应用于以 "test_"
为前缀的类的每个 方法?
换句话说,装饰器将应用于下面的test_1()
、test_2()
方法,但不适用于setUp()
。
class TestCase(object):
def setUp(self):
pass
def test_1(self):
print "test_1()"
def test_2(self):
print "test_2()"
最佳答案
在 Python 2.6 中,一个 class decorator绝对是要走的路。例如,对于这类任务,这是一个非常通用的任务:
import inspect
def decallmethods(decorator, prefix='test_'):
def dectheclass(cls):
for name, m in inspect.getmembers(cls, inspect.isfunction):
if name.startswith(prefix):
setattr(cls, name, decorator(m))
return cls
return dectheclass
@decallmethods(login_testuser)
class TestCase(object):
def setUp(self):
pass
def test_1(self):
print("test_1()")
def test_2(self):
print("test_2()")
会得到你想要的。在 Python 2.5 或更差的版本中,@decallmethods
语法不适用于类修饰,但如果使用其他完全相同的代码,您可以在 之后用以下语句替换它class TestCase
语句结束:
TestCase = decallmethods(login_testuser)(TestCase)
关于python - 将装饰器应用于类中的每个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2237624/