将单个装饰器应用于多种功能 [英] Apply a single decorator to multiple functions

查看:54
本文介绍了将单个装饰器应用于多种功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经进行了搜索,但是看到的结果却相反:将多个装饰器应用于单个函数。

I've searched for this, but the results I've seen involve the opposite: applying multiple decorators to a single function.

我想简化一下这种模式。有没有办法将此单个装饰器应用于多种功能?如果不是,我该如何重写上面的代码以减少重复性?

I'd like to simplify this pattern. Is there a way to apply this single decorator to multiple functions? If not, how can I rewrite the above to be less repetitious?

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函数并用结果修饰所有三个函数,则只需执行此操作即可。

If you want to make the "long" function call only once and decorate all three functions with the result, just do exactly that.

my_patch = patch('somelongmodulename.somelongmodulefunction')

@my_patch
def test_a(patched):
    pass

@my_patch
def test_b(patched):
    pass

这篇关于将单个装饰器应用于多种功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆