我正在使用从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__
,是否有解决此行为的方法?
2) Is there a workaround for this behavior (except of redefining
__repr__
in the subclass)?