代码之家  ›  专栏  ›  技术社区  ›  Developer

TypeError:接受0个位置参数,但给定了1个[重复]

  •  0
  • Developer  · 技术社区  · 7 年前

    我已经开始学习Python了。我创建了一个类,它有一个函数,在这个函数中我有一个字典。否我正在检查字典中是否存在键,检查后我将从函数返回一个值。

    "TypeError: first_func() takes 0 positional arguments but 1 was given"

    下面是我使用的代码:

    class myFirst:
        def first_func():
            flag=0
            phonebook = {
                "A" : 938477566,
                "B" : 938377264,
                "C" : 947662781
            }
            # testing code
            if "A" in phonebook:
                flag=1
            if "D" not in phonebook:
                flag = 0
            return flag
    
    myclassObj = myFirst()
    status = myclassObj.first_func()
    
    if status > 1:
        print ("Pass")
    else:
        print ("fail")
    
    3 回复  |  直到 7 年前
        1
  •  7
  •   vencaslac    5 年前

    方法(属于类的函数或过程)需要 self this 从其他语言来看,(除非明确定义为@staticmethod,但这看起来不像是您在这里要说的那样):

    class myFirst:
        def first_func(self): # here
            flag=0
            phonebook = {
                "A" : 938477566,
                "B" : 938377264,
                "C" : 947662781
            }
            # testing code
            if "A" in phonebook:
                flag=1
            if "D" not in phonebook:
                flag = 0
            return flag
    
    myclassObj = myFirst()
    status = myclassObj.first_func()
    
    if status > 1:
        print ("Pass")
    else:
        print ("fail")
    

    它应该和那个微小的变化一起工作。

    @staticmethod decorator(如果函数实际上不需要来自类实例的信息)您可以这样做:

    class myFirst:
        @staticmethod #here
        def first_func():
    

    您可以通过查看以下文档了解更多信息: https://docs.python.org/3/tutorial/classes.html

        2
  •  0
  •   Mark Xavier    7 年前

    错误是您没有在函数签名中引用self。将签名更改为

    def first_func(self):
        # rest of code
    
        3
  •  -1
  •   Hollywood    7 年前

    status ,然后将status与int进行比较-

    myClassObj = myFirst()
    if myClassObj.first_func():
        print "Pass"
    else
        print "Fail"
    

    复杂度增益非常小,但是当您可以使用函数返回的值时,没有理由将布尔值赋给另一个变量。