简体   繁体   中英

Python decorators calling functions in different classes

I am attempting to write a decorator which calls on two additional functions and runs them in addition to the function it is decorating in a specific order.

I have tried something along these lines:

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")

The final goal would be to have the decorator make the test run with the following flow setup > test > teardown. I know I am not calling on the setup and teardown correctly however. I would appreciate any help in how I should do this, I am new in using python and my knowledge of decorators involving arguments is limited.

Decorators on methods are applied when the class is being defined, which means that the setup and teardown methods are not bound at that time. This just means you need to pass in the self argument manually.

You'll also need to create an outer decorator factory; something that returns the actual decorator, based on your arguments:

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

Demo:

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM