簡體   English   中英

Python裝飾器在不同的類中調用函數

[英]Python decorators calling functions in different classes

我正在嘗試編寫一個裝飾器,該裝飾器除了要按特定順序裝飾的功能以外,還調用兩個附加功能並運行它們。

我已經嘗試了以下方法:

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,並且我對涉及參數的裝飾器的了解有限。

在定義類時,將使用方法上的裝飾器,這意味着那時沒有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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM