【问题标题】:In Python, can an object be used as a key in a dictionary? [duplicate]在 Python 中,对象可以用作字典中的键吗? [复制]
【发布时间】:2018-12-13 14:14:03
【问题描述】:

我有一些令人费解的代码正在尝试迁移到 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 oop dictionary


【解决方案1】:

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

Octopus 类必须以某种方式创建不可变实例。例如,它可能是元组的子类或使用 __slots__ 来做到这一点。

【讨论】:

  • 只有不可变类型可以用作键。
  • 是的。对不起。我的回答有点粗心。
【解决方案2】:

只有不可变类型可以用作 python 中的键。对于可能的解决方法,请将其包装为元组:

self.special_octopoda(<something>, Octopus(...))

或者让你的类可散列:

class Octopus:
    def __hash__(self):
        # hash implementation

【讨论】:

  • 不需要解决方法 - 正在工作,只是不在 TS
  • 需要解决方法!您必须将其包装成一个元组,否则该类应实现 __hash__
  • 他有代码在python中工作,它使用八达通实例作为键-他试图转换为TypeScript。 ergo:不需要解决方法...除非您提供 TypeScript-Workaround - 因为他不能在 TS 中执行此操作
  • @PatrickArtner 问题是In Python, can an object be used as a key in a dictionary?,而不是如何在 TS 中做到这一点。而且你不能使用任何对象作为python中的键......
  • 看问题。 I have code like this .... .. 后跟使用实例作为 dict 中的键的代码,然后是 it looks to me as though the Octopus object is being used as a key in a dictionary named special_octopoda. Is that allowed in Python? It certainly isn't in Typescript/Javascript. 他 has 代码在 python 中使用对象的实例...此代码的类必须已经是可散列以使代码正常工作。不需要解决方法。他对此感到困惑,因为他正在翻译到 TS,而这是不可能的。
猜你喜欢
  • 1970-01-01
  • 2011-11-25
  • 2012-03-18
  • 2011-03-08
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多