パラメータ付きのデコレータ?質問する

パラメータ付きのデコレータ?質問する

insurance_modeデコレータによる変数の転送に問題があります。次のデコレータ ステートメントで実行します。

@execute_complete_reservation(True)
def test_booking_gta_object(self):
    self.test_select_gta_object()

しかし残念ながら、このステートメントは機能しません。おそらく、この問題を解決するより良い方法があるかもしれません。

def execute_complete_reservation(test_case,insurance_mode):
    def inner_function(self,*args,**kwargs):
        self.test_create_qsf_query()
        test_case(self,*args,**kwargs)
        self.test_select_room_option()
        if insurance_mode:
            self.test_accept_insurance_crosseling()
        else:
            self.test_decline_insurance_crosseling()
        self.test_configure_pax_details()
        self.test_configure_payer_details

    return inner_function

ベストアンサー1

引数付きデコレータの構文は少し異なります。引数付きデコレータは、関数を受け取って別の関数を返す関数を返す必要があります。つまり、実際には通常のデコレータを返す必要があります。少しわかりにくいですよね? つまり、次のようになります。

def decorator_factory(argument):
    def decorator(function):
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            result = function(*args, **kwargs)
            more_funny_stuff()
            return result
        return wrapper
    return decorator

こここの件についてさらに詳しく読むことができます。呼び出し可能なオブジェクトを使用してこれを実装することも可能であり、それについてもそこで説明されています。

おすすめ記事