Python:跨函数共享变量

时间:2013-10-12 02:32:12

标签: python xml sax

我是python的新手。我想让这部分变量在函数中共享。

     publist = []
     publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5}
     article = False
     book = False
     inproceeding = False
     incollection = False
     pubidCounter = 0

我在哪里放置变量。我已尝试将其放置如下所示,但它表示存在错误。但是,将它们放在外面也会返回缩进错误。

import xml.sax


class ABContentHandler(xml.sax.ContentHandler):
     publist = []
     publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5}
     article = False
     book = False
     inproceeding = False
     incollection = False
     pubidCounter = 0

    def __init__(self):
        xml.sax.ContentHandler.__init__(self)

    def startElement(self, name, attrs):

        if name == "incollection":
            incollection = true
            publication["pubkey"] = attrs.getValue("pubkey")
            pubidCounter += 1

        if(name == "title" and incollection):
            publication["pubtype"] = "incollection"



    def endElement(self, name):
        if name == "incollection":

            publication["pubid"] = pubidCounter
            publist.add(publication)
            incollection = False

    #def characters(self, content):


def main(sourceFileName):
    source = open(sourceFileName)
    xml.sax.parse(source, ABContentHandler())


if __name__ == "__main__":
    main("dblp.xml")

2 个答案:

答案 0 :(得分:2)

当像这样放置它们时,你将它们定义为类的本地,因此你需要通过self

来检索它们

e.g。

def startElement(self, name, attrs):

    if name == "incollection":
        self.incollection = true
        self.publication["pubkey"] = attrs.getValue("pubkey")
        self.pubidCounter += 1

    if(name == "title" and incollection):
        self.publication["pubtype"] = "incollection"

如果您希望它们是全局的,您应该在类

之外定义它们

答案 1 :(得分:1)

将变量放在类定义中时,可以用这种方式引用这些变量:self.incollection(self是类实例)。如果你不这样做(只是通过名称引用这些变量,例如incollection),Python将尝试在全局范围内找到这些变量。因此,您可以将它们定义为全局,并在引用这些变量之前使用global关键字:

global incollection
incollection = true