我想复制冻结数据类的实例,仅更改一个字段(“功能更新”)。
这是我尝试过的
from dataclasses import dataclass, asdict
@dataclass(frozen = True)
class Pos:
start: int
end: int
def adjust_start(pos: Pos, delta: int) -> Pos:
# TypeError: type object got multiple values for keyword argument 'start'
return Pos(**asdict(pos), start = pos.start + delta)
adjust_start(Pos(1, 2), 4)
Run Code Online (Sandbox Code Playgroud)
我正在寻找什么:
dicts 转换更直接的方法?TypeError:如果有一种方法可以在功能上更新 kwargs,那么这是可行的。在 Scala 中,案例类(Scala 数据类)的功能更新可以这样完成pos.copy(start = pos.start + delta):
我想用 a 替换代码中字典中的字符串键,dataclass以便我可以为键提供元数据以进行调试。但是,我仍然希望能够使用字符串来查找字典。我尝试使用替换函数实现数据类__hash__,但是我的代码未按预期工作:
from dataclasses import dataclass
@dataclass(eq=True, frozen=True)
class Key:
name: str
def __hash__(self):
return hash(self.name)
k = "foo"
foo = Key(name=k)
d = {}
d[foo] = 1
print(d[k]) # Key Error
Run Code Online (Sandbox Code Playgroud)
这两个哈希函数是相同的:
print(hash(k) == hash(foo)) # True
Run Code Online (Sandbox Code Playgroud)
所以我不明白为什么这不起作用。
给出文档InventoryItem中的示例dataclasses。
from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
InventoryItem(name="Banana", unit_price=5, quantity_on_hand=3)
# OUTPUT:
# InventoryItem(name='Banana', unit_price=5, quantity_on_hand=3)
Run Code Online (Sandbox Code Playgroud)
如何覆盖标准输出消息,以便输出字符串
"3 Banana(s) at a unit price of 5."
Run Code Online (Sandbox Code Playgroud)
被展示?
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)] …
我想将一个类重构为数据类,这是我所拥有的:
class Tenant:
def __init__(self, tenant: dict, api_client: str) -> None:
self.name = tenant["name"]
self.tenant_id= tenant["id"]
self.subdomain = tenant["subdomain"]
self.api_client= api_client
Run Code Online (Sandbox Code Playgroud)
与数据类相同的类是什么?我尝试过类似的方法,但我不知道如何将此字典分为名称、租户 ID 和子域:
@dataclass
class Tenant:
tenant: dict
api_client: str
Run Code Online (Sandbox Code Playgroud)