我搜索过这个,但我看到的结果恰恰相反:将多个装饰器应用于单个函数。
我想简化这个模式。有没有办法将这个单个装饰器应用于多个函数?如果没有,我如何重写上面的内容以减少重复?
from mock import patch
@patch('somelongmodulename.somelongmodulefunction')
def test_a(patched):
pass # test one behavior using the above function
@patch('somelongmodulename.somelongmodulefunction')
def test_b(patched):
pass # test another behavior
@patch('somelongmodulename.somelongmodulefunction')
def test_c(patched):
pass # test a third behavior
from mock import patch
patched_name = 'somelongmodulename.somelongmodulefunction'
@patch(patched_name)
def test_a(patched):
pass # test one behavior using the above function
@patch(patched_name)
def test_b(patched):
pass # test another behavior
@patch(patched_name)
def test_c(patched):
pass # test a third behavior
最佳答案
如果你只想让“long”函数调用一次并用结果修饰所有三个函数,就这样做吧。
my_patch = patch('somelongmodulename.somelongmodulefunction')
@my_patch
def test_a(patched):
pass
@my_patch
def test_b(patched):
pass
关于python - 将单个装饰器应用于多个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30563807/