You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python OOP计算器__init__变量操作问题:自定义运算触发无效操作错误

问题分析与修复方案

核心错误点

  • 循环内重复初始化计算器实例:你在循环里每次都新建calculator()对象,之前通过add_operation添加的sqrt、exponentiation、logarithm等操作完全没被用到,每次都是只带四则运算的全新实例,自然触发无效符号错误。
  • calculate方法覆盖输入参数:方法已经接收了num1和num2,却又用input重新获取值,完全忽略传入的参数,属于逻辑冗余。
  • 单参数操作不兼容现有逻辑:sqrt、logarithm是单参数运算,但calculate强制要求传入两个参数,调用时会报错。

修复后的完整代码

import math

class calculator():
    def __init__(self):
        self.dictionary = {"+": lambda x, y: x + y,
                           "-": lambda x, y: x - y,
                           "*": lambda x, y: x * y,
                           "/": lambda x, y: x / y}

    def add_operation(self, symbol, function):
        if symbol not in self.dictionary:
            self.dictionary[symbol] = function

    def calculate(self, symbol, *args):
        if symbol not in self.dictionary:
            raise ValueError("Invalid operation symbol")
        
        for num in args:
            if not isinstance(num, (int, float)):
                raise ValueError("Invalid input numbers")
        
        return self.dictionary[symbol](*args)

# 仅初始化一次计算器并添加高级运算
calc = calculator()
calc.add_operation("sqrt", lambda x: math.sqrt(x))
calc.add_operation("pow", lambda x, y: math.pow(x, y))
calc.add_operation("log", lambda x: math.log(x))

while True:
    symbol = input("What operation would you like to perform? (+, -, *, /, sqrt, pow, log) ")
    
    if symbol in ["sqrt", "log"]:
        num = float(input("Enter the number: "))
        result = calc.calculate(symbol, num)
    elif symbol in ["+", "-", "*", "/", "pow"]:
        num1 = float(input("What is the first number? "))
        num2 = float(input("What is the second number? "))
        result = calc.calculate(symbol, num1, num2)
    else:
        print("Invalid operation symbol, try again.")
        continue
    
    print("Result:", result)

    new_op = input("Would you like to perform another calculation? (yes/no) ")
    if new_op.lower() == "no":
        break

关键修复说明

  • 移到循环外初始化计算器:确保添加的高级运算全程有效,不会被重复初始化清空。
  • 修改calculate为可变参数:用*args兼容单参数和多参数运算,不再强制要求两个数字。
  • 按需获取输入:根据操作类型判断需要输入的数字数量,避免单参数运算传入多余值。
  • 简化操作符号:把长名称的操作改成更易输入的短符号,提升用户体验。

内容的提问来源于stack exchange,提问作者SEIF c

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 05:52:51