Dataclass子类不继承__repr__

Dataclass subclass does not inherit __repr__

我正在使用从 Python 3.7 向后移植的 Python dataclasses 模块。 我偶然发现了这种行为,其中数据类子类不继承 __repr__:

from dataclasses import dataclass

@dataclass
class Person:
    name: str

    def __repr__(self):
        return f'{self.__class__.__qualname__}({self.name})'

    def print_something(self):
        return self.name

@dataclass
class Employee(Person):
    title: str

这是输出

In [21]: e = Employee(name='Dmitry', title='Systems Engineer')

In [22]: p = Person(name='Dmitry')

In [23]: repr(e)
Out[23]: "Employee(name='Dmitry', title='Systems Engineer')"

In [24]: p = Person(name='Dmitry')

In [25]: repr(p)
Out[25]: 'Person(Dmitry)'

In [26]: p.print_something()
Out[26]: 'Dmitry'

In [27]: e = Employee(name='Dmitry', title='Systems Engineer')

In [28]: repr(e)
Out[28]: "Employee(name='Dmitry', title='Systems Engineer')"

In [29]: e.print_something()
Out[29]: 'Dmitry'

1) 为什么会这样?
2) 这种行为是否有解决方法(除了在子类中重新定义 __repr__)?

发生这种情况是因为 dataclass 自动添加了一个 __repr__ 方法,恰好 几乎与您的基础方法完全相同 class,所以你没有注意到。通过repr=False for dataclass 不添加repr:

In [5]: from dataclasses import dataclass
   ...:
   ...: @dataclass(repr=False)
   ...: class Person:
   ...:     name: str
   ...:
   ...:     def __repr__(self):
   ...:         return f'{self.__class__.__qualname__}({self.name})'
   ...:
   ...:     def print_something(self):
   ...:         return self.name
   ...:
   ...: @dataclass(repr=False)
   ...: class Employee(Person):
   ...:     title: str
   ...:

In [6]: Person('foo')
Out[6]: Person(foo)

In [7]: Employee('foo', 'bar')
Out[7]: Employee(foo)