我正在使用从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__
除外)?
答案 0 :(得分:4)
之所以会这样,是因为dataclass
自动添加了一个__repr__
方法,该方法只是发生,几乎与您在基类中拥有的方法完全一样,因此您没有注意。为repr=False
传递dataclass
,不要添加重复:
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)