我想定義一個帶有引數的裝飾器,如果引數丟失,則會引發錯誤。
這是對簡化示例的天真嘗試:
def decorator_with_arg(a=None):
if a is None :
raise ValueError("Missing argument in decorator")
def decorator(func):
def wrapped_func(x):
return func(x a)
return wrapped_func
return decorator
但是當我在沒有引數的情況下使用這個裝飾器時,它不會引發任何錯誤:
@decorator_with_arg
def simple_func(x):
return 2*x
simple_func(1)
如何引發例外?
uj5u.com熱心網友回復:
您沒有正確使用您的裝飾器,在您的代碼simple_func(1)中只會回傳wrapped_func,因為@decorator_with_arg只會這樣做:
simple_func = decorator_with_arg(simple_func)
# ^ this is passing a=simple_func
# now simple_func is the decorator function defined inside decorator_with_arg
您需要呼叫yourdecorator_with_arg以使其回傳decorator,然后將其用于裝飾函式:
@decorator_with_arg(100)
def simple_func(x):
return 2*x
print(simple_func(1)) # 202
在任何情況下,如果你想強制一個引數,只需宣告它而不使用默認值:
def decorator_with_arg(a):
# ...
并洗掉if a is None支票。
如果你想避免使用@decorator_with_arg而不是的錯誤@decorator_with_arg(),你可以添加一個檢查以確保a不是一個函式:
def decorator_with_arg(a):
if callable(a):
raise TypeError("Incorrect use of decorator")
def decorator(func):
def wrapped_func(x):
return func(x a)
return wrapped_func
return decorator
@decorator_with_arg
def func():
return 1
# TypeError: Incorrect use of decorator
@decorator_with_arg(123)
def func():
return 1
# All fine
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426256.html
上一篇:NumberFormatExcpetion同時使用Long.parseLong()將base-2數字(作為字串)決議為base-10Longint
