2014-12-03 95 views
-3
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) 

错误:为什么这个代码doent运行,并有错误:

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__' 
+3

你可以发现在你引用'f'和's'的方式和你引用'dict'的方法之间的任何区别吗? – 2014-12-03 15:01:52

回答

2

不要对你的变量dict,这是一个内置。

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

+0

哇,非常感谢你,它现在正常工作,thaaaaaaank你:) – user4320545 2014-12-03 15:21:48