为什么此代码不运行并出现错误:

时间:2014-12-03 14:59:22

标签: python calculator

class cal2:
    def __init__(self, a, b):
        self.f = a
        self.s = b
        dict = {"add": self.add, "sub": self.sub, "mul": self.mul, "div": self.div}

    def add(self, w, q):
        return w + q

    def sub(self, w, q):
        return w - q

    def mul(self, w, q):
        return w * q

    def div(self, w, q):
        return w / q

    def calculator(self, fun):

        return dict[fun](self.f, self.s)

from cal2 import cal2

if __name__ == "__main__":

    request = raw_input("Type the Function and numbers :")
    method = request[0:3]
    l = [0, 0]
    k = 0

    for word in request.split():
        if word.isdigit():
            l[k] = word
            k = k + 1
    c = cal2(l[0],l[1])

    print  c.calculator(method)

错误:

Type the Function and numbers :add 8 7
Traceback (most recent call last):
  File "C:/Users/user/PycharmProjects/test/work_example/main.py", line 16, in <module>
    print  c.calculator(method)
  File "C:\Users\user\PycharmProjects\test\work_example\cal2.py", line 24, in calculator
    return dict[fun](self.f, self.s)
TypeError: 'type' object has no attribute '__getitem__'

1 个答案:

答案 0 :(得分:2)

不要为变量dict命名,这是内置的。

此外,您未能将其变为实例变量,它应该是例如self._ops = { "add": self.add ...