Python TypeError: NoneType object is not callable E

2024-05-29 04:51:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我只是一个Python初学者。我得到以下错误,并怀疑它与我用作switch case的字典有关(因为python不提供switch)。以下是我的代码:

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

Tags: inselfaddfordef错误rangearithmetic
2条回答

替换为:

selector[self.choice]()  

致:

selector[self.choice]

演示:

>>> def test():
...     return "hello"
... 
>>> my_dict = {1:test()}
>>> my_dict[1]
'hello'

当你这样做的时候

self.add()

您正在调用方法(您将得到一个结果)。如果要指定方法,请删除()

selector = {
            "1" :   self.add,
            "2" :   self.substract, 
            "3" :   self.multiply,
            "4" :   self.divide,
            "5" :   self.modulo
            }

相关问题 更多 >

    热门问题