您想要实现的计算器功能有很多种。下面是一个简单的计算器实现的示例代码,可以实现基本的四则运算功能:
```python
class Calculator:
def __init__(self):
self.operations = {
'+': self.add,
'-': self.subtract,
'*': self.multiply,
'/': self.divide
}
def add(self, a, b):
return a + b
def subtract(self, a, b):
return a - b
def multiply(self, a, b):
return a * b
def divide(self, a, b):
if b == 0:
return 'Error: Division by zero'
return a / b
def calculate(self, operator, a, b):
if operator not in self.operations:
return 'Error: Invalid operator'
operation = self.operations[operator]
return operation(a, b)
# 测试示例
calculator = Calculator()
result = calculator.calculate('+', 10, 5)
print(result) # 输出: 15
result = calculator.calculate('-', 10, 5)
print(result) # 输出: 5
result = calculator.calculate('*', 10, 5)
print(result) # 输出: 50
result = calculator.calculate('/', 10, 5)
print(result) # 输出: 2
result = calculator.calculate('/', 10, 0)
print(result) # 输出: Error: Division by zero
```
上面的示例代码使用了一个字典来存储不同的运算符对应的函数,然后通过调用相应的函数来执行对应的运算。计算器类还提供了一个 `calculate` 方法来接收运算符、操作数,并返回计算结果。