【发布时间】: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