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')

また、最後の行で、現在の作業ディレクトリにあるファイルを渡していますが、これはファイルをアドレス指定する正しい方法ですか?

4

2 に答える 2

8

_ init _の名前に _ が多すぎます。コンストラクターの宣言は次のようにする必要があります。

def __init__(self, title, number):

いいえ:

def __init___(self, title, number):

余分なアンダースコア記号に注意してください。

于 2012-08-10T15:53:31.517 に答える
4

タイプミスがあります - ここに 3 つのアンダースコアがあります:

def __init___(self, title, number):

次のようにする必要があります。

def __init__(self, title, number):

名前 と完全には一致しないため__init__、Python はデフォルトのコンストラクターdef __init__(self).

于 2012-08-10T15:54:15.000 に答える