我正在用 Python 构建一个计算器。我正在网上学习一个教程,参加该课程真的很酷。但在这个代码页上,eval 使其成为代码的一部分有点复杂。
def _eq(self):
displayText = self.display.text()
if not isValidNumber(displayText):
print('Sem nada para a direita')
return
self._right = float(displayText)
self.equation = f'{self._left} {self._op} {self._right}'
result = 0.0
try:
result = eval(self.equation)
except ZeroDivisionError:
print('Zero Division Error')
self.display.clear()
self.info.setText(f'{self.equation} = {result}')
self._left = result
self._right = None
我使用了一些尝试通过gpt chat生成的代码,但结果是相似的。最大的问题就在这行代码:
result = eval(self.equation)
我不知道你的其余代码是什么样的,但在你分享的片段中,你似乎还没有定义
self._left
。了解您遇到的错误类型也会很有帮助。
此外,您应该考虑使用
eval()
的替代方案,因为它可以运行任意代码,这被认为是一个安全漏洞。此外,它可能会对您的性能产生影响,因为它在运行时解析和解释新代码。
编写评估方程的方法而不是使用
eval()
可能会有所帮助。
该方法可能类似于以下内容:
def evaluate_expression(left_operand, operator, right_operand):
# addition
if operator == '+':
return left_operand + right_operand
# subtraction
elif operator == '-':
return left_operand - right_operand
# multiplication
elif operator == '*':
return left_operand * right_operand
# division
elif operator == '/':
try:
return left_operand / right_operand
except ZeroDivisionError:
print('Zero Division Error')
return None
# other operands you might want to implement
else:
print('Unsupported operator')
return None