TypeError: __init__()仅接受1个参数(给出了3个)pyXML

4
我最近开始学习如何使用Python解析XML文件。我参考了这篇教程:http://pyxml.sourceforge.net/topics/howto/node12.html
当我运行下面的代码时,出现了错误:
Traceback (most recent call last):
  File "C:\Users\Name\Desktop\pythonxml\tutorials\pythonxml\pyxml sourceforge\5.1 Comic Colection\SearchForComic.py", line 30, in -toplevel-
    dh = FindIssue('sandman', '62')
TypeError: __init__() takes exactly 1 argument (3 given)

代码:

from xml.sax import saxutils

class FindIssue(saxutils.DefaultHandler):
    def __init___(self, title, number):
        self.search_title, self.search_number = title, number

def startElement(self, name, attrs):
    #if it's not a comic element, ignore it
    if name!= 'comic': return

        # look for the title and number sttributes (see text)
        title = attrs.get('title', None)
        number = attrs.get('number', None)
        if (title == self.search_title and
            number == self.search_number):
                print title, '#' +str (number), 'found'

from xml.sax import make_parser
from xml.sax.handler import feature_namespaces

if __name__ == '__main__':
        #Create a parser
        parser = make_parser()

    #tell the parser that we are not interested in XML namespaces
        parser.setFeature(feature_namespaces, 0)

    #create the handler
    dh = FindIssue('sandman', '62')

    #tell the parse to use our handler
    parser.setContentHandler(dh)

    #parse the input
    parser.parse('collection.xml')

最后一行代码中,我将文件传递给了当前工作目录中,这样写是正确的吗?

2个回答

8
你的名字中有太多下划线_,构造函数声明应该如下所示:

You've got too many _ in the name of _init_. 构造函数的声明应为:

def __init__(self, title, number):

注意:

def __init___(self, title, number):

请注意多了一个下划线符号。

4
这是一种令人困惑的错误。正如 izkata 指出的那样,如果 __init__ 不存在,Python 就会退回到只接受 self 参数的默认构造函数,因此 Python 抱怨函数参数过多,而你认为它们是正确的数量。 - Joe Day

4

您有一个错别字 - 这里有三个下划线:

def __init___(self, title, number):

应该是:

def __init__(self, title, number):

因为它与名称__init__并不完全匹配,所以Python只知道默认构造函数def __init__(self)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接