from dataclasses import dataclass
@dataclass
class coordinate:
x: int
y: int
objects = {}
pos = coordinate(0, 0)
objects[pos] = "A"
pos.x += 1 # Changing the current position I am looking at
objects[pos] = "B"
pos.y += 1
objects[pos] = "C"
for position in objects:
print(position, objects[position])
Run Code Online (Sandbox Code Playgroud)
这会抛出TypeError: unhashable type: 'coordinate'.
设置@dataclass(frozen=True, eq=True)投掷dataclasses.FrozenInstanceError: cannot assign to field 'x'。
最后,使用@dataclass(unsafe_hash=True)结果:
coordinate(x=1, y=1) C
coordinate(x=1, y=1) C
coordinate(x=1, y=1) C
Run Code Online (Sandbox Code Playgroud)
实现此目的的一种方法是使用objects[(pos.x, pos.y)] …