私はPythonの初心者で、簡単な計算クラスを練習しています。
このコードは、ユーザーがコマンドラインに2つの数字と1つの演算子を入力すると、答えが表示されることを前提としています。関数add()、subtract()、multiply()、divide()で4行を出力するのはなぜだろうか。すべてを呼び出すのではなく、辞書に入れるだけです。誰かが私のためにそれを説明してもらえますか?解決策も教えていただければ幸いです。前もって感謝します!
WindowsPowerShellからの出力は次のとおりです。
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)