在 Python > 3.7 中,您可以使用 dataclass。也可以注解dataclass。
在这个特定的例子中,Node 引用了它自己,如果你运行它,你会得到
NameError: name 'Node' is not defined
要克服此错误,您必须包括:
from __future__ import annotations
它必须是模块中的第一行。在 Python 4.0 及更高版本中,您不必包含 annotations
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node
right: Node
@property
def is_leaf(self) -> bool:
"""Check if node is a leaf"""
return not self.left and not self.right
例子:
node5 = Node(5, None, None)
node25 = Node(25, None, None)
node40 = Node(40, None, None)
node10 = Node(10, None, None)
# balanced tree
node30 = Node(30, node25, node40)
root = Node(20, node10, node30)
# unbalanced tree
node30 = Node(30, node5, node40)
root = Node(20, node10, node30)