Python 类封装计算器:简化数学运算
class Calculator:
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
def multiply(self, x, y):
return x * y
def divide(self, x, y):
if y != 0:
return x / y
else:
return 'Error: division by zero'
使用方法:
calculator = Calculator()
result = calculator.add(5, 3)
print(result) # 输出:8
result = calculator.subtract(5, 3)
print(result) # 输出:2
result = calculator.multiply(5, 3)
print(result) # 输出:15
result = calculator.divide(5, 3)
print(result) # 输出:1.6666666666666667
result = calculator.divide(5, 0)
print(result) # 输出:Error: division by zero
原文地址: https://www.cveoy.top/t/topic/pZdC 著作权归作者所有。请勿转载和采集!