用python补全代码class Number(): def __init__(self, n1, n2): self.__n1 = n1 self.__n2 = n2 def addition(self): m1 = self.__n1 + self.__n2 print('%d+%d=%d' % (self.__n1,self.__n2,m1)) def subtration(self): m2 = self.__n1 - self.__n2 n1, n2, op = input().split(",") mm = Number(int(n1), int(n2)) if op == 'add': elif op == 'sub': mm.subtration() else: print("error!")
时间: 2024-02-10 10:10:26 浏览: 138
根据题目中的要求,下面是代码的完整实现:
```python
class Number():
def __init__(self, n1, n2):
self.__n1 = n1
self.__n2 = n2
def addition(self):
m1 = self.__n1 + self.__n2
print('%d+%d=%d' % (self.__n1, self.__n2, m1))
def subtration(self):
m2 = self.__n1 - self.__n2
print('%d-%d=%d' % (self.__n1, self.__n2, m2))
n1, n2, op = input().split(",")
mm = Number(int(n1), int(n2))
if op == 'add':
mm.addition()
elif op == 'sub':
mm.subtration()
else:
print("error!")
```
这里定义了一个Number类,包含addition和subtration方法。在创建Number对象mm时,我们从标准输入中读入了n1、n2和op三个变量,并将n1和n2转换为整数类型。如果op为'add',我们调用mm的addition方法,否则我们调用subtration方法。在addition和subtration方法中,我们分别计算出m1和m2,并输出相应的表达式和结果。如果op既不是'add'也不是'sub',我们输出"error!"。
阅读全文