什么时候信息丰富的 __repr__ 会很危险?

When would an informative __repr__ be dangerous?

我无法理解为什么默认 __repr__ 的实现没有提供更多信息。

这个答案在 州

having a default for repr which would act like: return "%s(%r)" % (self.__class__, self.__dict__) would have been too dangerous (for example, too easy to get into infinite recursion if objects reference each other).

这种情况会是

instance = Class(); instance.attr = instance

这对我来说更像是一个错误。可能发生这种情况的有效用例是什么?

当节点可以有引用其父节点的子节点时,这是某些层次结构的有效用例

例如,

root = Node()
child = Node()
child.parent=root
root.children = [child]

考虑一棵 DOM 树,其中一个节点包含对其子节点的引用,并且每个子节点都包含对其父节点的引用。

(它也发生在兄弟姐妹之间 nextSibling/previousSibling。)

任何类型的 object 双向引用都可能发生这种情况。例如,表示家庭关系的 class,其中每个人都引用了他们的配偶,或者 parents 引用了他们的 children 而 children 引用了他们的配偶parents.

PHP 的 print_r() 执行您的建议;请参阅 以了解有人试图打印代表 HTML DOM 元素的 object 的问题。