我是python初学者,正在练习一个简单的计算课。
这段代码假设当用户在命令行中输入 2 个数字和 1 个运算符时,它会告诉你答案。我只是想知道为什么它在函数 add()、subtract()、multiply() 和 divide() 中打印 4 行。我只是将它们放入字典中,而不是全部调用。有人可以为我解释一下吗?向我展示解决方案也很棒。提前致谢!
这是 windows power shell 的输出:
PS D:\misc\Code\python\mystuff> python .\CalculationTest.py
Please input a number:
>1
Please input a operator(i.e. + - * /):
>+
Please input another number:
>2
Adding 1 + 2 #why it shows these 4 lines?
Subtracting 1 - 2
Multiplying 1 * 2
Dividing 1 / 2
3
这是我的代码:
class Calculation(object):
def add(self, a, b):
print "Adding %d + %d" % (a, b)
return a + b
def subtract(self, a, b):
print "Subtracting %d - %d" % (a, b)
return a - b
def multiply(self, a, b):
print "Multiplying %d * %d" % (a, b)
return a * b
def divide(self, a, b):
if b == 0:
print "Error"
exit(1)
else:
print "Dividing %d / %d" % (a, b)
return a / b
def get_result(self, a, b, operator):
operation = {
"+" : self.add(a, b), # I didn't mean to call these methods,
"-" : self.subtract(a, b), # but it seems that they ran.
"*" : self.multiply(a, b),
"/" : self.divide(a, b),
}
print operation[operator]
if __name__ == "__main__":
print "Please input a number:"
numA = int(raw_input(">"))
print "Please input a operator(i.e. + - * /):"
operator = raw_input(">")
print "Please input another number:"
numB = int(raw_input(">"))
calc = Calculation()
#print calc.add(numA, numB)
calc.get_result(numA, numB, operator)