我有一个包装函数,如下所示:
def check(func):
@wraps(func)
def wrap(*args, **kwargs):
while 1:
try:
return func(*args, **kwargs)
except AssertionError:
print('Invalid Input')
except ValueError:
print('Invalid Input')
return wrap
但是我想让错误输入可自定义。 我试过这个:
def check(func, errorText='Invalid Input’):...
像这样使用它:
@check(errorText = 'Input must be in {}'.format(tiles))
得到了这个:
Traceback (most recent call last):
@check(errorText = 'Input must be in {}'.format(tiles))
TypeError: check() missing 1 required positional argument: ‘func'
我试过了:
...
def wrap(*args, errorText = ‘Invalid Input’, **kwargs):
...
没有错误,但它仍然打印Invalid Input
作为错误消息。
以下是我正在使用的一些代码:
@check
def getInt(_min, _max, _type, errorText = ’Number is not in correct range'):
n = int(input("Enter {} number (inbetween {} and {}): ".format(_type, _min, _max)))
assert _min <= n <= _max
return n
@check
def setAt(board, new, errorText = ’Space is already filled.'):
row = getInt(1, 5, 'row')-1
col = getInt(1, 5, 'column')-1
assert board[row][col] == '.'
board[row][col] = new
@check
def getTile(errorText = ‘Input must be in {}’.format(tiles)):
tile = input("Enter tile to choose: ").upper()
assert tile in tiles
return tile