Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:接受0个位置参数,但提供了1个_Python_Python 3.x - Fatal编程技术网

Python TypeError:接受0个位置参数,但提供了1个

Python TypeError:接受0个位置参数,但提供了1个,python,python-3.x,Python,Python 3.x,我已经开始学习Python了。我创建了一个类,它有一个函数,在这个函数中我有一个字典。否我正在检查字典中是否存在键,检查后我将从函数返回一个值 现在我可以尝试访问函数,但当我这样做时,我得到一个错误“TypeError:first_func()接受0个位置参数,但给出了1” 以下是我正在使用的代码: class myFirst: def first_func(): flag=0 phonebook = { "A" : 9384775

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

现在我可以尝试访问函数,但当我这样做时,我得到一个错误
“TypeError:first_func()接受0个位置参数,但给出了1”

以下是我正在使用的代码:

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")
方法(属于类的函数或过程)需要一个
self
参数,您可能熟悉其他语言中的
这个
(除非明确定义为@staticmethod,但它看起来不像您在这里要说的那样)如下:

它应该与这个微小的变化一起工作

如果您想使用
@staticmethod
装饰器(如果函数实际上不需要类实例的信息),您可以这样做:

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

您可以通过检查此处的文档了解更多信息:

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

def first_func(self):
    # rest of code

除了添加自变量外,还可以考虑缩短代码。您的函数返回一个布尔值,您将该值指定给

status
,然后将status与int进行比较。相反,您可以这样做来保存几行-

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

复杂度增益非常小,但是如果您只需要使用函数返回的值,就没有理由将布尔值指定给另一个变量。

感谢您对此的解释
myClassObj = myFirst()
if myClassObj.first_func():
    print "Pass"
else
    print "Fail"