对使用类或函数感到困惑:使用 lxml 和 Python 编写 XML 文件
我需要使用 lxml 和 Python 编写 XML 文件。
但是,我不知道是使用 class
来执行此操作还是使用函数。重点是,这是我第一次开发合适的软件,决定在哪里以及为什么使用 class
仍然显得很神秘。
我将阐述我的观点。
例如,请考虑我编写的以下基于函数的代码,用于将子元素添加到 etree 根。
from lxml import etree
root = etree.Element('document')
def createSubElement(text, tagText = ""):
etree.SubElement(root, text)
# How do I do this: element.text = tagText
createSubElement('firstChild')
createSubElement('SecondChild')
正如预期的那样,其输出是:
<document>
<firstChild/>
<SecondChild/>
</document>
但是,正如您可以注意到的注释,我不知道如何使用这种方法设置文本变量。
使用 class
是解决这个问题的唯一方法吗?如果是的话,您能给我一些关于如何实现这一目标的建议吗?
I need to write XML files using lxml and Python.
However, I can't figure out whether to use a class
to do this or a function. The point being, this is the first time I am developing a proper software and deciding where and why to use a class
still seems mysterious.
I will illustrate my point.
For example, consider the following function based code I wrote for adding a subelement to a etree root.
from lxml import etree
root = etree.Element('document')
def createSubElement(text, tagText = ""):
etree.SubElement(root, text)
# How do I do this: element.text = tagText
createSubElement('firstChild')
createSubElement('SecondChild')
As expected, the output of this is:
<document>
<firstChild/>
<SecondChild/>
</document>
However as you can notice the comment, I have no idea how to do set the text variable using this approach.
Is using a class
the only way to solve this? And if yes, can you give me some pointers on how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下代码有效:
使用类而不是函数主要与在类的实例中保持状态有关(在极少数用例中,如果不需要状态保持,类将有意义),这与您的问题无关 - 正如代码所示,您的问题只是您没有将任何名称绑定到从
SubElement
调用返回的元素,因此您当然无法在函数的其余部分中进一步操作该元素(例如,通过设置其text
属性)。The following code works:
Using a class rather than a function has mostly to do with keeping state in the class's instances (in very few use cases will a class make sense if there's no state-keeping required), which has nothing to do with your problem -- as the code shows, your problem was simply that you were not binding any name to the element returned from the
SubElement
call, and therefore of course you were unable to further manipulate that element (e.g. by setting itstext
attribute) in the rest of your function.