【问题标题】:How can I print Etree Element node object's attribute and its values instead of memory address of etree.Element?如何打印 Etree Element 节点对象的属性及其值而不是 etree.Element 的内存地址?
【发布时间】:2020-01-18 19:14:58
【问题描述】:

我有这样的情况:

import xml.etree.cElementTree as etree


class Universe(object):
    def get_node(self, label, attribs):
        return etree.Element(
            type(label), label=label, **attribs)

class Planet(Universe):
    def __init__(self, name, nom=0):
        super(Planet, self).__init__()
        self._name = name
        self._nom = nom

    def label(self):
        return self._name

    def no_of_moons(self):
        return self._nom

class Earth(object):
    def __init__(self):
        self.life_support = True
        self.presence_of_water = True
        planet_earth = Planet(self, nom=1)
        self.node = planet_earth.get_node(self, self.__dict__)

earth = Earth()
print earth.node

所以我得到这样的地球输出<Element <class 'Earth'> at 0x108fa1ed0>

但我想要的输出如下:<Element Earth(life_support=True, nom=True)>

现在我知道我可以覆盖 __repr__ 以得到类似上面的结果,但是 etree.Element 是 'builtin_function_or_method 类型的函数,我不知道如何输出对调试有用的东西。

【问题讨论】:

    标签: python lxml repr


    【解决方案1】:

    您必须为相关对象实现 repr 函数。

    要更改 Earth 的输出,您可以将 repr 函数添加到 earth 类。

    直接更改元素的 repr 效果不佳,因为此类似乎不允许进行猴子修补(许多类允许猴子修补实例方法)

    您必须适应自己的需求的一个例子是:

    class Earth(object):
        def __init__(self):
            self.life_support = True
            self.presence_of_water = True
            planet_earth = Planet(self, nom=1)
            self.node = planet_earth.get_node(self, self.__dict__)
    
        def __repr__(self):
            return("<Element %s(life_support=%s, nom=%s)" %
                   (self.__class__.__name__,
                    self.life_support,
                    self.node.tag,  # display xml tag of element
                    # or self.node.attrib["name"],
                   ))
    
    earth = Earth()
    print(earth)  # this looks now nicer
    print(earth.node)  # this still looks ugly
    etree.dump(earth.node)  # sends the xml of the given node to stdout
    

    请注意,上面的代码是用python3测试的,而不是用python2测试的

    【讨论】:

    • 本例 earth.node 返回&lt;Element &lt;class 'Earth'&gt; at 0x101d2eed0&gt; &lt;type 'builtin_function_or_method'&gt;
    • 嗯,你知道你的输出仍然是我得到的,但我想要的是 我想要输出像在开幕帖中。
    • 道歉。如果您确实打印 earth(而不是 earth.node),我的输出看起来只会有所不同如果您真的坚持对节点元素本身具有不同的 repr,那么您必须扩展元素类。将在几分钟内向您发送一个示例。扩展一个类应该遵循stackoverflow.com/questions/15404256/…
    • Element 类对猴子补丁有很强的抵抗力。所以我的想法行不通。对于调试,您可以打印出:(etree.dump(earth.node) 但 Element 的重载效果不佳
    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2015-10-28
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多