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

kur*_*rka 5 python python-3.x python-dataclasses

我试图比较从公共基类(也是@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
Run Code Online (Sandbox Code Playgroud)

但是,我得到:

TypeError: '<' not supported between instances of 'ChildA' and 'ChildB'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

che*_*ner 5

您应该自己定义比较方法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
Run Code Online (Sandbox Code Playgroud)


JLe*_*o46 0

ca.a < cb.a
Run Code Online (Sandbox Code Playgroud)

两者都具有来自父类的属性“a”,使用“.a”访问该属性