Python 如何打印Etree元素节点对象';属性及其值,而不是etree.Element的内存地址?

Python 如何打印Etree元素节点对象';属性及其值,而不是etree.Element的内存地址?,python,lxml,repr,Python,Lxml,Repr,我的情况是这样的: 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, no

我的情况是这样的:

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
所以我得到地球的输出像这样

但我希望输出如下:


现在我知道我可以重写
\uuu repr\uuuu
以得到类似于上面的结果,但是
etree.Element
内置函数或方法类型的函数,我不知道如何输出对调试有用的东西。

您必须为所讨论的对象实现repr函数

要更改Earth的输出,可以在Earth类中添加repr函数

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

你必须适应自己需要的一个例子是:

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
类地球(对象):
定义初始化(自):
自我生命支持=真实
self.presence\u水=True
行星地球=行星(自身,名称=1)
self.node=planet\u earth.get\u node(self,self.\u dict\u)
定义报告(自我):

return(“本例earth.node返回
您知道您的输出仍然是我得到的,但我想要的是我想要的输出,如开篇文章中所示。抱歉。如果您打印earth(而不是earth.node),则我的输出看起来会有所不同)如果您真的坚持要为节点元素本身使用不同的repr,那么您必须扩展元素类。几分钟后将向您发送一个示例。扩展类应该可以很好地执行以下操作:元素类很难进行monkeypatching。因此,我的想法行不通。对于调试,您可以打印:(etree.dump(earth.node),但元素的重载效果不好