如何将自定义拆分字符串的scalc函数整合至含基础数学方法的calculator类?
问题:字符串解析计算功能该单独建类还是整合到现有计算器类?
我写了一个scalc函数,它能从单个字符串(格式如"N1, N2, operator")里提取三个参数,拆分后执行计算并返回结果。现在纠结是给它单独创建类,还是整合到现有的接收两个输入的calculator类里?尝试整合的时候遇到了困难,scalc里包含strip格式化处理,相关代码如下:
class calculator: def __init__(self,a,b): self.Num1 = a self.Num2 = b def add(self): return self.Num1 + self.Num2 def subtract(self): return self.Num1 - self.Num2 def multiply(self): return self.Num1 * self.Num2 def divide(self): return self.Num1 / self.Num2 def allInOne(self): result = { "add": self.Num1 + self.Num2, "sub": self.Num1 - self.Num2, "mult": self.Num1 * self.Num2, "div": self.Num1 / self.Num2} return result def start(self): print('which calculation do you want to perform?''\n' '1: Add' '\n' '2: Subtract''\n' '3: Multiply' '\n' '4: Divide' '\n' '5: allInOne') choice = int(input("Enter your choice: ")) switcher = {1: self.add(), 2: self.subtract(), 3: self.multiply(), 4: self.divide(), 5: self.allInOne()} function = switcher.get(choice) return function a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) function = calculator(a,b) pass print(function.start()) ## 以下是要添加的scalc函数 def scalc(p1): # p1 will be a string like this "N1, N2, operator" items = p1.split(",") operand1 = float(items[0].strip()) operand2 = float(items[1].strip()) operator = items[2].strip() if operator == "+": return sum1(operand1, operand2) elif operator == "-": return difference1(operand1, operand2) elif operator == "*": return product1(operand1, operand2) elif operator == "/": return quotient1(operand1, operand2)
解决方案:整合到现有
calculator类更合理 直接把scalc的逻辑改成calculator类的静态方法即可,这样既不用重复定义计算函数,又能把所有计算功能收拢到同一个类里,结构更清晰。修改后的代码如下:
class calculator: def __init__(self,a,b): self.Num1 = a self.Num2 = b def add(self): return self.Num1 + self.Num2 def subtract(self): return self.Num1 - self.Num2 def multiply(self): return self.Num1 * self.Num2 def divide(self): if self.Num2 == 0: return "Error: 除数不能为0" return self.Num1 / self.Num2 def allInOne(self): result = { "add": self.Num1 + self.Num2, "sub": self.Num1 - self.Num2, "mult": self.Num1 * self.Num2, "div": self.divide() if self.Num2 !=0 else "Error: 除数不能为0"} return result def start(self): print('which calculation do you want to perform?''\n' '1: Add' '\n' '2: Subtract''\n' '3: Multiply' '\n' '4: Divide' '\n' '5: allInOne') choice = int(input("Enter your choice: ")) # 修复提前执行方法的问题,延迟调用 switcher = {1: self.add, 2: self.subtract, 3: self.multiply, 4: self.divide, 5: self.allInOne} function = switcher.get(choice) return function() if function else "无效选择" @staticmethod def scalc(p1): # 解析输入字符串 items = p1.split(",") # 处理格式错误 if len(items) !=3: return "Error: 输入格式错误,请使用'N1, N2, 运算符'格式" try: operand1 = float(items[0].strip()) operand2 = float(items[1].strip()) except ValueError: return "Error: 输入的不是有效数字" operator = items[2].strip() # 直接执行运算,避免依赖未定义函数 if operator == "+": return operand1 + operand2 elif operator == "-": return operand1 - operand2 elif operator == "*": return operand1 * operand2 elif operator == "/": if operand2 ==0: return "Error: 除数不能为0" return operand1 / operand2 else: return f"Error: 不支持的运算符'{operator}'" # 使用示例 # 原有功能使用 a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) calc = calculator(a,b) print(calc.start()) # 新增scalc功能使用 input_str = input("输入计算字符串(格式:N1, N2, 运算符):") print(calculator.scalc(input_str))
关键修改点说明:
- 把
scalc改成静态方法,无需实例化就能调用,也可在实例内使用 - 修复原代码中
switcher提前执行所有计算方法的问题,改用延迟调用 - 添加格式校验和错误处理,避免输入异常导致程序崩溃
- 移除对未定义
sum1、difference1等函数的依赖,直接复用运算逻辑
如果非要单独建类也可行,但完全没必要——所有功能都围绕计算展开,整合在同一个类里更符合代码内聚性原则,维护起来也更方便。
内容的提问来源于stack exchange,提问作者Clown Face
相关产品推荐
相关产品推荐

