我正在使用dataclasses
从 Python 3.7 向后移植的 Python 模块。我偶然发现了数据类子类不继承的这种行为__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__
在子类中重新定义除外)?