Python 装饰器调用不同类中的函数

标签 python function arguments decorator

我正在尝试编写一个装饰器,它除了按特定顺序装饰的函数之外还调用两个附加函数并运行它们。

我已经尝试过以下方法:

class common(): 
    def decorator(setup, teardown, test):
        def wrapper(self):
            setup
            test
            teardown
        return wrapper

class run():
    def setup(self):
        print("in setup")

    def teardown(self):
        print("in teardown")

    @common.decorator(setup, teardown)
    def test(self):
        print("in test")

最终目标是让装饰器按照以下流程进行测试运行:设置 > 测试 > 拆卸。我知道我没有正确调用安装和拆卸。如果我能帮助我解决这个问题,我将不胜感激,我是Python的新手,而且我对涉及参数的装饰器的了解有限。

最佳答案

方法上的装饰器在定义类时应用,这意味着当时未绑定(bind) setupteardown 方法。这只是意味着您需要手动传入 self 参数。

您还需要创建一个外部装饰器工厂;根据您的参数返回实际装饰器的东西:

def decorator(setup, teardown):
    def decorate_function(test):
        def wrapper(self):
            setup(self)
            test(self)
            teardown(self)
        return wrapper
    return decorate_function

演示:

>>> def decorator(setup, teardown):
...     def decorate_function(test):
...         def wrapper(self):
...             setup(self)
...             test(self)
...             teardown(self)
...         return wrapper
...     return decorate_function
... 
>>> class run():
...     def setup(self):
...         print("in setup")
...     def teardown(self):
...         print("in teardown")
...     @decorator(setup, teardown)
...     def test(self):
...         print("in test")
... 
>>> run().test()
in setup
in test
in teardown

关于Python 装饰器调用不同类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610718/

相关文章:

python - 为什么我不能将对字典值的直接引用传递给函数?

command-line - 如何将命令行参数传递给 PowerShell ps1 文件

java - Mockito 匹配任何类参数

python - NumPy 数组到列表的转换

python net-snmp加载mibs

vba - 将函数结果复制到 Sub

drupal 链接到 View 依赖于参数

python - Sympy 不会用符号除以其平方根来简化表达式

python - 使用 awk 进行模式检查

javascript - HTML 表单中的 onClick JavaScript 函数