首页 > 解决方案 > 在 Python 中,对象可以用作字典中的键吗?

问题描述

我有一些令人费解的代码正在尝试迁移到 Typescript。看这个:

    def add_Octopus(self, code, cracker, fate, description, arm_number, ink_content, fate_pointer, churlishness=None):
    self.special_octopoda[
        Octopus(code, description, arm_number, fate, churlishness, self, ink_content, fate_pointer)] = fate_pointer, cracker

在我看来,Octopus 对象好像被用作名为 special_octopoda 的字典中的键。Python允许这样做吗?它当然不在 Typescript/Javascript 中。

标签: pythonoopdictionary

解决方案


是的,您可以使用任何不可变对象作为 Python 字典中的键。

Octopus 类必须以某种方式创建不可变实例。例如,它可能是元组的子类或用于__slots__执行此操作。


推荐阅读