为什么这些函数在字典中运行

时间:2013-02-19 08:57:01

标签: python dictionary

我是一名初学者,我正在练习一个简单的计算课程。

这段代码假定当用户在命令行输入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)

3 个答案:

答案 0 :(得分:2)

你说你并不是要打电话给这些方法。但你做到了。你写了

self.add(a, b)

并且调用add,因为它使用调用运算符()。在填充字典时,您正在调用每个算术运算符方法。

如果您想捕获该方法而不是调用它,则需要将self.add放入dict

然后当你想要调用方法时,你会这样做:

print operation[operator](a, b)

此时我们正在使用调用操作符()并提供参数。

总而言之,您的功能如下所示:

def get_result(self, a, b, operator):
    operation = {
        "+" : self.add,      
        "-" : self.subtract, 
        "*" : self.multiply,
        "/" : self.divide,
    }
    print operation[operator](a, b)

由于dict永远不会变化,因此将它作为类属性并仅将其初始化一次可能更为明智。

我并不认为你的实例在这里非常有用。您没有在任何地方提到self。这表明这些方法可能更好static methods

答案 1 :(得分:2)

请改为:

def get_result(self, a, b, operator):
    operation = {
        "+" : self.add,
        "-" : self.subtract,
        "*" : self.multiply,
        "/" : self.divide,
    }
    print operation[operator](a, b)

注意在创建字典后如何将实际方法调用(带(a, b))移动到。你使用它的方式,你调用每个方法并将结果存储在字典中,而不是存储方法,然后只调用你想要的方法。

答案 2 :(得分:0)

以下代码:

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),
}

会急切地评估所有值,因为这是python的工作方式。你想做的事:

operation = {
    "+" : self.add,
    "-" : self.subtract,
    "*" : self.multiply,
    "/" : self.divide,
}

然后调整其余代码以仅调用适当的方法。

如果你想用原始风格编码,你需要一种具有惰性评估语义的语言,例如haskell。