8

我正在使用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__在子类中重新定义除外)?

4

1 回答 1

12

发生这种情况是因为dataclass自动添加了一个__repr__方法,该方法恰好是您在基类中拥有的方法,所以您没有注意到。通过repr=Falsedataclass添加代表:

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)
于 2018-10-31T19:51:07.457 回答