小编Spw*_*ack的帖子

使用移动 x,y 坐标数据类作为字典键的 Pythonic 方法是什么?

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)] …

python python-dataclasses

0
推荐指数
1
解决办法
47
查看次数

标签 统计

python ×1

python-dataclasses ×1