简体   繁体   中英

Problem with defining variables in python

I'm trying to write some xml by this piece of code

docs = XmlReportGenerator()
docs.AddMatchRow('FC Barcelona','Madryt','5:0')
docs.Save()

and I wrote my own method:

from lxml import etree

class XmlReportGenerator:
    """"""
    root = etree.Element('results')
    doc = etree.ElementTree(root)

    #----------------------------------------------------------------------
    def __init__(self):

        """""" 

    def AddMatchRow(self,teamA,teamB, score):
        pageElement = etree.SubElement(root,'Flight',teamA, teamB, score)

        """"""

    def Save(self,path = None):
        outFile = open('Matches.xml', 'w')
        doc.write(outFile) 

NameError: global name 'root' is not defined Process terminated with an exit code of 1 done

NameError: global name 'doc' is not defined Process terminated with an exit code of 1 done

Am I missing something? I'm a newbie in python (I have more experience in c#).

Python is explicit. Instance variables must be prepended with self. . Class variables must be prepended with then name of the class.

Here's a fixed version. The original SubElement call was incorrect as well:

from lxml import etree

# derive from 'object' if Python 2.X (it is default in Python 3.X)
class XmlReportGenerator(object):

    def __init__(self):
        # clearer to init instance variables here.
        self.root = etree.Element('results')
        self.doc = etree.ElementTree(self.root)

    def AddMatchRow(self,teamA,teamB, score):
        # Need self.root here
        pageElement = etree.SubElement(self.root,'Flight')
        # Added data elements (or did you want attributes?)
        etree.SubElement(pageElement,'teamA').text = teamA
        etree.SubElement(pageElement,'teamB').text = teamB
        etree.SubElement(pageElement,'score').text = score

    def Save(self,path = None):
        outFile = open('Matches.xml', 'w')
        # Need self.doc here
        self.doc.write(outFile)

# This code will run if the script is executed directly,
# but will be skipped if the script is imported by another script.
if __name__ == '__main__':
    docs = XmlReportGenerator()
    docs.AddMatchRow('FC Barcelona','Madryt','5:0')
    docs.Save()

self is there for a reason. Use self.root , not root

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