【发布时间】:2021-01-06 18:06:30
【问题描述】:
我知道标题很混乱,所以我以二叉搜索树为例:
使用普通类定义
# This code passed mypy test
from typing import Generic, TypeVar
T = TypeVar('T')
class BST(Generic[T]):
class Node:
def __init__(
self,
val: T,
left: 'BST.Node',
right: 'BST.Node'
) -> None:
self.val = val
self.left = left
self.right = right
以上代码通过mypy测试。
使用dataclass
但是,当我尝试使用dataclass 来简化Node 的定义时,代码在mypy 测试中失败了。
# This code failed to pass mypy test
from dataclasses import dataclass
from typing import Generic, TypeVar
T = TypeVar('T')
class BST(Generic[T]):
@dataclass
class Node:
val: T
left: 'BST.Node'
right: 'BST.Node'
mypy 给了我这个错误信息:(test_typing.py:8 是val: T 行)
test_typing.py:8: error: Type variable "test_typing.T" is unbound
test_typing.py:8: note: (Hint: Use "Generic[T]" or "Protocol[T]" base class to bind "T" inside a class)
test_typing.py:8: note: (Hint: Use "T" in function signature to bind "T" inside a function)
查明问题
# This code passed mypy test, suggest the problem is the reference to `T` in the dataclass definition
from dataclasses import dataclass
from typing import Generic, TypeVar
T = TypeVar('T')
class BST(Generic[T]):
@dataclass
class Node:
val: int # chose `int` just for testing
left: 'BST.Node'
right: 'BST.Node'
上面的代码再次通过了测试,所以我认为问题在于数据类定义中对@987654332@的引用。有谁知道将来如何解决这个问题以实现我最初的目标?
【问题讨论】:
-
在 BST 中定义 Node 有什么原因吗?
-
@MisterMiyagi 只想将
Node设为私有。我认为这在 Java 中很常见。 -
请注意,它根本不是私有的。它只会有一个稍长的全局名称,并且会受到类范围规则的影响(您刚刚发现了其中一个)。
-
是的,我知道 python 不支持真正的私有化。不过还是谢谢提醒。
标签: python python-typing python-dataclasses