简体   繁体   中英

Python: Share variables across functions

I am new to python. I would like to make this part of the variables shared across the functions.

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

Where do i place the variables in these. I have tried placing it as shown below but it says there is an error with indendation. However, placing them outside returns an error too of indentation.

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

When placing them like that you define them as local for the class, thus you need to retrieve them through self

eg

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"

If you would rather for them to be global, you should define them outside the class

When you place the variables in the class definition, you can reference these variables in this way: self.incollection ( self is the class instance ). If you don't do this( just reference these variables by their name, such as incollection ), Python will try to find the these variables in global scope. So you can define them to be global and use the global keyword before reference these variables:

global incollection
incollection = true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM