I use the codes below to print the structure of a tree. It do works, but I wonder in the last line how it recognize self.left
and self.right
as a variable rather than just a string? In my knowledge, variable should be enclosed by {}
in f-string, but this differs.
class Node:
def __init__(self, value: int, parent: Node | None) -> None:
self.value = value
self.parent = parent
self.right: Node | Node = None
self.left: Node | Node = None
def __repr__(self) -> str:
if self.left is None and self.right is None:
return str(self.value)
return pformat({f"{self.value}": (self.left, self.right)}, indent=1)