【问题标题】:How to recursively display object properties in a dictionary format?如何以字典格式递归显示对象属性?
【发布时间】:2020-11-16 13:44:27
【问题描述】:

我正在尝试打印类实例中所有属性的字典,但是,当有另一个类作为属性之一时,我也无法打印其属性的字典。这对我来说有点难以解释,所以我认为举个例子会更容易理解。

class A:
  def __init__(self):
    self.x = "x"
    self.b = B(self)
  def __str__(self):
    self.__dict__["b"] = vars(self.__dict__["b"])
    return str(self.__dict__)
  
class B:
  def __init__(self, a):
    self.a = a
    self.y = "y"
    self.c = C(self)
  def __str__(self):
    self.__dict__["c"] = vars(self.__dict__["c"])
    return str(temp)

class C:
  def __init__(self, b):
    self.b = b
    self.z = "z"
  def __str__(self):
    return str(self.__dict__)

print(A())

输出:

{'x': 'x', 'b': {'a': <__main__.A object at 0x7f1913e47460>, 'y': 'y', 'c': <__main__.C object at 0x7f1913e2dbe0>}}

预期输出:

{'x': 'x', 'b': {'a': <__main__.A object at 0x7fe0becea460>, 'y': 'y', 'c': {'b': <__main__.B object at 0x7f8e7224bc40>, 'z': 'z'}}}

最终,我希望我的输出是这样的:

{'x': 'x', 'b': {'y': 'y', 'c': {'z': 'z'}}

因此,如果有人可以通过推断我在中间步骤中的错误或直接解决问题以使我达到我想要的结果来提供帮助,我将不胜感激。谢谢!

【问题讨论】:

标签: python python-3.x


【解决方案1】:

第二个你可以使用它或根据你的需要改变它:

from ast import literal_eval
class A:
    def __init__(self):
        self.x = "x"
        self.b = B(self)

    def __str__(self):
        o = {}
        for x in self.__dict__:
            if isinstance(self.__dict__[x], str):
                o[x] = self.__dict__[x]
        o['b'] = literal_eval(str(self.b))
        return str(o)


class B:
    def __init__(self, a):
        self.a = a
        self.y = "y"
        self.c = C(self)

    def __str__(self):
        o = {}
        for x in self.__dict__:
            if isinstance(self.__dict__[x], str):
                o[x] = self.__dict__[x]
        o['c'] = literal_eval(str(self.c))
        return str(o)


class C:
    def __init__(self, b):
        self.b = b
        self.z = "z"

    def __str__(self):
        o = {}
        for x in self.__dict__:
            if isinstance(self.__dict__[x], str):
                o[x] = self.__dict__[x]
        return str(o)
print(A())

首先你应该使用str 而不是var

class A:
  def __init__(self):
    self.x = "x"
    self.b = B(self)
  def __str__(self):
    self.__dict__["b"] = str(self.__dict__["b"])
    return str(self.__dict__)

class B:
  def __init__(self, a):
    self.a = a
    self.y = "y"
    self.c = C(self)
  def __str__(self):
    self.__dict__["c"] = str(self.__dict__["c"])
    return str(self.__dict__)

class C:
  def __init__(self, b):
    self.b = b
    self.z = "z"
  def __str__(self):
    return str(self.__dict__)

print(A())

【讨论】:

  • 您回答的第一个代码块,打印 {'x': 'x', 'b': '{\'y\': \'y\', \'c\': "{\'z\': \'z\'}"}'},其中括号已转义,而不是像普通字典那样打印。
  • @ShivangPatel,我编辑它以打印正确的值。
猜你喜欢
  • 2021-01-01
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多