简体   繁体   English

混淆使用类或函数:使用lxml和Python编写XML文件

[英]Confused as to use a class or a function: Writing XML files using lxml and Python

I need to write XML files using lxml and Python. 我需要使用lxml和Python编写XML文件。

However, I can't figure out whether to use a class to do this or a function. 但是,我无法弄清楚是否使用class来执行此操作或函数。 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. 关键是,这是我第一次开发一个合适的软件,并决定在哪里以及为什么使用一个class似乎仍然是神秘的。

I will illustrate my point. 我会说明我的观点。

For example, consider the following function based code I wrote for adding a subelement to a etree root. 例如,考虑我编写的以下基于函数的代码,用于将子元素添加到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')

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? 使用class是解决这个问题的唯一方法吗? And if yes, can you give me some pointers on how to achieve this? 如果是的话,你能给我一些关于如何实现这一目标的指示吗?

The following code works: 以下代码有效:

def createSubElement(text, tagText = ""):
    elem = etree.SubElement(root, text)
    elem.text = tagText

createSubElement('firstChild', 'first one')
createSubElement('SecondChild', 'second one')

print etree.tostring(root)

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 (eg by setting its text attribute) in the rest of your function. 使用类而不是函数主要与在类的实例中保持状态有关(在极少数用例中,如果不需要保持状态 ,则类会有意义),这与您的问题无关 - 如代码显示,您的问题只是您没有将任何名称绑定到从SubElement调用返回的元素,因此当然您无法在函数的其余部分中进一步操作该元素(例如,通过设置其text属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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