我正在尝试编写一个装饰器,它除了按特定顺序装饰的函数之外还调用两个附加函数并运行它们。
我已经尝试过以下方法:
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) 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
关于Python 装饰器调用不同类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610718/