我正在尝试编写一个装饰器,它调用另外两个函数并运行它们以及它按特定顺序装饰的函数。
我尝试过这些方法:
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的新手,我对涉及参数的装饰器的知识是有限的。
答案 0 :(得分:2)
在定义类时应用了方法上的装饰器,这意味着当时不绑定setup
和teardown
方法。这只是意味着您需要手动传递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