python - 在 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 中。
解决方案
是的,您可以使用任何不可变对象作为 Python 字典中的键。
Octopus 类必须以某种方式创建不可变实例。例如,它可能是元组的子类或用于__slots__
执行此操作。
推荐阅读
- authentication - WSO2 APIM 身份在 SAML SSO 响应的 NameID 中回复用户名或域/用户名
- angular - 如何在 ionic4 应用程序中使用原生谷歌地图?
- .net - 查找大数组的声明
- facebook-graph-api - Instagram:无法通过 ID 获取标记的媒体对象
- python - 如何将类实例分配给一个变量并在其他类中使用它
- pattern-matching - 案例表达式和“重载”参数计数
- javascript - 如何动态检查空参数?
- javascript - 如何在打字稿中缩短接口名称?
- php - 如何自然地对多维数组进行排序?
- r - 如何在 R 中使导入文件更加动态