装饰器不返回函数

问题描述 投票:0回答:1

我有一项涉及装饰师的学校作业。我写了这段代码:

def valid_input(func):
    def wrapper(x):
        if x in [0, 1, 2, 3, 4]:
            return func(x)
        else:
            print("Invalid Input")
    return wrapper

def show_operation(func):
    def wrapper(x, y):
        operation = func.__name__
        print(f"Performing {operation}")
        return func(x, y)
    return wrapper

@valid_input
def calc(op):
    if op == 0:
        print("Quitting calculator...")
        quit()
    else:
        x = get_operand()
        y = get_operand()
        if op == 1:
            return add(x, y)
        elif op == 2:
            return sub(x, y)
        elif op == 3:
            return mult(x, y)
        elif op == 4:
            return div(x, y)

def menu():
    print("Enter an operation:")
    print("1 Add\n2 Subtract\n3 Multiply\n4 Divide\n0 Quit")
    return int(input(">"))

def get_operand():
    return int(input("Enter an operand:"))

@show_operation
def add(x, y):
    return x + y

@show_operation
def sub(x, y):
    return x - y

@show_operation
def mult(x, y):
    return x * y

@show_operation
def div(x, y):
    return x / y

while True:
    op = menu()
    result = calc(op)
    print(f"Result: {result}\n")

问题是如果用户输入无效的输入,会出现一些错误。看来我的装饰器不能正常使用它们的相关功能。

代码有什么问题,我该如何解决?

python python-decorators
1个回答
0
投票

这里的主要问题是没有进行任何异常处理,尤其是在获取操作数时。你需要做的是在异常发生时捕获异常:

def get_operand():
    try:
        return int(input("Enter an operand:"))
    except ValueError:
        raise ValueError("Invalid input. Please enter a number.")

现在,当为操作数输入不正确的值时,脚本将打印一条消息并重新引发异常。从技术上讲,您可以使用

pass
立即处理异常,但通常最好将异常传播到主函数,以便最终用户可以决定他们想用它们做什么。

所以现在,你还需要修改你的

while
循环来处理异常:

while True:
    op = menu()
    try:
        result = calc(op)
        print(f"Result: {result}\n")
    except ValueError:
        pass
© www.soinside.com 2019 - 2024. All rights reserved.