在Python中,对象可以用作字典中的键吗?

2024-05-14 20:12:18 发布

您现在位置: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

在我看来,好像章鱼对象被用作一个名为special\ octopoda的字典中的键。Python允许这样做吗?当然不是在Typescript/Javascript中。你知道吗


Tags: selfnumbercodedescriptioncontentarmspecialtypescript
2条回答

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

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

或者使您的类可散列:

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

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

Octopus类必须以某种方式创建不可变的实例。例如,它可能是tuple的一个子类,或者使用__slots__来实现这一点。你知道吗

相关问题 更多 >

    热门问题