绕过ElementTree [英] Passing around an ElementTree
问题描述
在程序中,我需要在程序的各种功能中使用ElementTree对象.
In my program, I need to make use of an ElementTree object in various functions in my program.
更具体地说,我正在这样做:
More specifically, I am doing this:
tree = etree.parse('somefile.xml')
我正在程序中传递这棵树.
I am passing this tree around in my program.
我想知道这是否是一种好方法,或者我可以这样做:
I was wondering whether this is a good approach, or can I do this:
- 创建全局树(我来自 C ++背景,我知道全局是 不好)
- 根据需要再次创建树.
- Create a global tree (I come from a C++ background and I know global is bad)
- Create the tree again wherever required.
或者我的方法还可以吗?
Or is my approach ok?
推荐答案
在Python中(消除复杂性,为您的C ++背景打个比方),所有对象都是通过引用传递的.而且由于树"是一个对象,因此您只传递了引用.现在,如果您有一组在同一棵树上操作的相关方法,则可能要考虑创建一个以该树对象作为成员的类.
In Python, (eliding complexities, making an analogy for your C++ background) all objects are passed by reference. And since "tree" is an object, you're only passing the reference. Now, if you have a group of related methods that operate on the same tree, you might want to consider creating a class with that tree object as a member.
此外,这是我上面提到的复杂性的快速参考: http://www .testingreflections.com/node/view/5126
Also, here's a quick reference to the complexities I glossed over above: http://www.testingreflections.com/node/view/5126
这篇关于绕过ElementTree的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!