【发布时间】:2015-10-27 01:55:55
【问题描述】:
我在 Python 中使用此代码将装饰器应用于类的所有方法:
import inspect
def decallmethods(decorator, prefix='test_'):
def dectheclass(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
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()"
这很好用。但是,我想将一些kwargs 传递给我想申请的装饰器。
所以,我想要类似的东西:
@decallmethods(login_testuser, data="TEST") on class
它应用于方法的装饰器变为:
@login_testuser(data="TEST")
【问题讨论】:
-
为什么不直接用
setUp方法登录测试用户(并使用unittest)?