【问题标题】:Python decorators calling functions in different classesPython 装饰器在不同的类中调用函数
【发布时间】:2015-02-21 00:37:50
【问题描述】:

我正在尝试编写一个装饰器,它调用两个额外的函数,并在它以特定顺序装饰的函数之外运行它们。

我已经尝试过这些方面的一些东西:

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 的新手,我对涉及参数的装饰器的了解是有限的。

【问题讨论】:

标签: python function arguments decorator


【解决方案1】:

在定义类时应用方法上的装饰器,这意味着 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2017-12-11
    • 2020-03-19
    • 1970-01-01
    • 2017-09-13
    • 2017-01-15
    • 2017-08-01
    相关资源
    最近更新 更多