python中定义变量的问题
我试图通过这段代码编写一些xml,
docs = XmlReportGenerator()
docs.AddMatchRow('FC Barcelona','Madryt','5:0')
docs.Save()
并且编写了自己的方法:
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 进程终止,退出代码为 1 完成
名称错误:未定义全局名称“doc” 进程终止,退出代码为 1 完成
我错过了什么吗?我是 python 的新手(我在 c# 方面有更多经验)。
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#).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Python 是明确的。实例变量必须以
self.
开头。类变量必须前面加上类的名称。这是一个固定版本。原始的
SubElement
调用也不正确: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:self
的存在是有原因的。使用self.root
,而不是root
self
is there for a reason. Useself.root
, notroot