我只是Python的初学者。我收到以下错误,并怀疑它与我用作切换案例的字典有关(因为python不提供切换)。以下是我的代码:
class Arithmetic:
a,b,choice = 0,0,0
def __init__(self):
print "\n\n"
for num in range(30):
print "*",
print "\n"
print "Welcome to CLC (Command Line Calculator)"
print "\n"
for num in range(30):
print "*",
print "\n"
def menu(self):
print "1. Add"
print "2. Substract"
print "3. Multiply"
print "4. Divide"
print "5. Modulo"
print "6. Exit \n\n"
self.choice = raw_input("Enter Your Choice: ")
if self.choice == '0':
exit("Thank you for using the program")
selector = {
"1" : self.add(),
"2" : self.substract(),
"3" : self.multiply(),
"4" : self.divide(),
"5" : self.modulo()
}
selector[self.choice]()
def add(self):
print "Add called"
def substract(self):
print "Substract called"
def multiply(self):
print "Multiply called"
def divide(self):
print "Divide called"
def modulo(self):
print "Modulo called"
def main(self):
while self.choice != '6':
self.menu()
a = Arithmetic()
a.menu()
错误是:
Traceback (most recent call last):
File "arithmetics.py", line 75, in <module>
a.menu()
File "arithmetics.py", line 43, in menu
selector[self.choice]()
TypeError: 'NoneType' object is not callable
答案 0 :(得分:2)
当你这样做时
self.add()
你正在调用方法(你会得到一个结果)。如果要指定方法,请删除()
:
selector = {
"1" : self.add,
"2" : self.substract,
"3" : self.multiply,
"4" : self.divide,
"5" : self.modulo
}
答案 1 :(得分:1)
替换这个:
selector[self.choice]()
为:
selector[self.choice]
演示:
>>> def test():
... return "hello"
...
>>> my_dict = {1:test()}
>>> my_dict[1]
'hello'