Skip to main content
 首页 » 编程设计

python之Python中不可变对象(immutable对象)的类型是什么(针对mypy)

2025年05月04日12mfryf

我总是在我的 Python 程序中使用 mypy。

不可变对象(immutable对象)的类型(来自 typing)是什么,可以用作字典键的对象?

回到上下文,我想写一个从字典继承的类,我有以下代码

class SliceableDict(dict): 
    def __getitem__(self, attr:Any) -> Any: 
        return super().__getitem__(attr) 

在那种情况下,类型提示是毫无用处的,不是吗?

谢谢

请您参考如下方法:

dict 的键是 hashable (参见 the first sentence of the docs on dict ),可哈希类型为 typing.Hashable , collections.abc.Hashable 的别名.