我对Python还不熟悉。我想让这部分变量在函数间共享。你知道吗
publist = []
publication = {"pubid" : 1, "title" : 2, "year" : 3, "pubtype" : 4, "pubkey" :5}
article = False
book = False
inproceeding = False
incollection = False
pubidCounter = 0
我应该把这些变量放在哪里。我试着把它如下所示,但它说,有一个与indundation错误。但是,将它们放在外部会返回缩进错误。你知道吗
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")
当这样放置它们时,您将它们定义为类的本地对象,因此需要通过
self
检索它们例如
如果您希望它们是全局的,那么应该在类之外定义它们
在类定义中放置变量时,可以这样引用这些变量:
self.incollection
(self是类实例)。如果不这样做(只需按名称引用这些变量,如incollection
),Python将尝试在全局范围内查找这些变量。因此,您可以将它们定义为全局变量,并在引用这些变量之前使用global关键字:相关问题 更多 >
编程相关推荐