gpt4 book ai didi

python - 如何比较具有相同继承的@dataclass 的实例子类

转载 作者:行者123 更新时间:2023-12-05 03:48:18 29 4
gpt4 key购买 nike

我正在尝试比较从公共(public)基类(也是@dataclass)继承的两个数据类。

继承类的字段是自己特有的,比较时不考虑;我只想比较基类属性。

这是我的尝试:

from dataclasses import dataclass, field

@dataclass(order=True)
class Base:
a: float

@dataclass(order=True)
class ChildA(Base):
attribute_a: str = field(compare=False)

@dataclass(order=True)
class ChildB(Base):
attribute_b: str = field(compare=False)


ca = ChildA(1, 'a')
cb = ChildB(2, 'b')
ca < cb

但是,我得到:

TypeError: '<' not supported between instances of 'ChildA' and 'ChildB'

我该如何解决这个问题?

最佳答案

你应该自己定义Base的比较方法; dataclass 创建的方法要求参数具有完全相同的类型。

from functools import total_ordering

@total_ordering
@dataclass(eq=False)
class Base:
a: float


# Both of these are oversimplified. At the very
# least, handle the error resulting from `other`
# not having an `a` attribute.

def __eq__(self, other):
return self.a == other.a

def __lt__(self, other):
return self.a < other.a

关于python - 如何比较具有相同继承的@dataclass 的实例子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64482975/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com