【发布时间】:2021-12-09 20:29:01
【问题描述】:
import math
class Calculator():
def __init__(self, num1=0.0, op=None, num2=0.0, result=None):
self.num1 = num1
self.op = op
self.num2 = num2
self.result = result
def main(self, num1, op, num2, result):
if op == "+":
result = float(num1) + float(num2)
print(result)
elif op == "-":
result = float(num1) - float(num2)
print(result)
elif op == "*":
result = float(num1) * float(num2)
print(result)
elif op == "/" and float(num2) == 0:
result = None
print("You can't divide by zero")
p.main(self, num1, op, num2, result)
elif op == "/" and float(num2) != 0:
result = float(num1) / float(num2)
print(result)
elif op == "power":
result = float(num1)**float(num2)
print(result)
else:
print("invalid input")
while True:
p = Calculator()
p.main(num1=input("Write a number: "),
op=input("+ or - or * or / or power: "),
num2=input("Write another number: "),
result=None)
ans = input("Would you like to do another equation: ")
if ans == "yes":
p.main()
ans = input("Would you like to do another equation: ")
elif ans == "no":
exit()
我尝试将 5 除以 6 以测试一切是否正常,但出现此错误:
Traceback(最近一次调用最后一次): 文件“d:\Visual Studio Code\Projects\HelloWorld python\tempCodeRunnerFile.py”,第 37 行,在 p.main(num1=input("写一个数字:"), 文件“d:\Visual Studio Code\Projects\HelloWorld python\tempCodeRunnerFile.py”,第 24 行,在 main p.main(self, num1, op, num2, 结果) TypeError: Calculator.main() 接受 5 个位置参数,但给出了 6 个
【问题讨论】:
-
这个程序适用于我,在 python 3.8 中没有例外。我运行了一些输入并将漂亮的答案打印到控制台。
-
与错误无关,但为什么
result是函数的参数? -
这是因为 OP 仍处于混乱阶段,他们正在弄清楚函数/OOP 如何工作。我相信他们会到达那里。 :P
-
@Samwise 我同意。我的评论只是朝着正确的方向轻推。
标签: python