dataclasses组合属性的方式使您无法在基类中使用带有默认值的属性,然后在子类中使用没有默认值的属性(位置属性).
这是因为属性是从MRO的底部开始组合的,并按照第一次看到的顺序建立一个有序的属性列表;覆盖将保留在其原始位置.所以Parent
从['name', 'age', 'ugly']
开始,其中ugly
有一个默认值,然后Child
将['school']
添加到列表的末尾(ugly
已经在列表中).这意味着您将得到['name', 'age', 'ugly', 'school']
,因为school
没有默认值,这将导致__init__
的参数列表无效.
这一点记录在PEP-557 Dataclasses中,inheritance下:
当数据类由@dataclass
decorator创建时,它以反向MRO(即从object
开始)查看该类的所有基类,并为找到的每个数据类将该基类中的字段添加到字段的有序映射中.添加所有基类字段后,它会将自己的字段添加到有序映射中.所有生成的方法都将使用这种组合的、计算有序的字段映射.因为字段是按插入顺序排列的,所以派生类会覆盖基类.
Specification岁以下:
如果一个没有默认值的字段跟在一个有默认值的字段后面,则将提高TypeError
.无论是在单个类中发生,还是作为类继承的结果,这都是正确的.
为了避免这个问题,你有一些 Select .
第一种 Select 是使用单独的基类,将带有默认值的字段强制放在MRO顺序的后面位置.无论如何,避免直接在要用作基类的类上设置字段,例如Parent
.
以下类层次 struct 起作用:
# base classes with fields; fields without defaults separate from fields with.
@dataclass
class _ParentBase:
name: str
age: int
@dataclass
class _ParentDefaultsBase:
ugly: bool = False
@dataclass
class _ChildBase(_ParentBase):
school: str
@dataclass
class _ChildDefaultsBase(_ParentDefaultsBase):
ugly: bool = True
# public classes, deriving from base-with, base-without field classes
# subclasses of public classes should put the public base class up front.
@dataclass
class Parent(_ParentDefaultsBase, _ParentBase):
def print_name(self):
print(self.name)
def print_age(self):
print(self.age)
def print_id(self):
print(f"The Name is {self.name} and {self.name} is {self.age} year old")
@dataclass
class Child(Parent, _ChildDefaultsBase, _ChildBase):
pass
通过将字段拖出separate个基类,其中包含没有默认值的字段和有默认值的字段,以及仔细 Select 的继承顺序,您可以生成一个MRO,将所有没有默认值的字段放在有默认值的字段之前.Child
的反向MRO(忽略object
)为:
_ParentBase
_ChildBase
_ParentDefaultsBase
_ChildDefaultsBase
Parent
请注意,Parent
没有设置任何新字段,因此在这里,它在字段列表顺序中最后一个字段并不重要.字段没有默认值的类(_ParentBase
和_ChildBase
)位于字段有默认值的类(_ParentDefaultsBase
和_ChildDefaultsBase
)之前.
结果是Parent
和Child
个类,其中一个sane字段更旧,而Child
仍然是Parent
的子类:
>>> from inspect import signature
>>> signature(Parent)
<Signature (name: str, age: int, ugly: bool = False) -> None>
>>> signature(Child)
<Signature (name: str, age: int, school: str, ugly: bool = True) -> None>
>>> issubclass(Child, Parent)
True
因此,您可以创建这两个类的实例:
>>> jack = Parent('jack snr', 32, ugly=True)
>>> jack_son = Child('jack jnr', 12, school='havard', ugly=True)
>>> jack
Parent(name='jack snr', age=32, ugly=True)
>>> jack_son
Child(name='jack jnr', age=12, school='havard', ugly=True)
另一种 Select 是只使用带有默认值的字段;通过提高__post_init__
分之一,仍然可以在错误中不提供school
值:
_no_default = object()
@dataclass
class Child(Parent):
school: str = _no_default
ugly: bool = True
def __post_init__(self):
if self.school is _no_default:
raise TypeError("__init__ missing 1 required argument: 'school'")
但这改变了场秩序;school
在ugly
之后结束:
<Signature (name: str, age: int, ugly: bool = True, school: str = <object object at 0x1101d1210>) -> None>
类型提示判断器will抱怨_no_default
不是字符串.
你也可以使用attrs
project,这是启发dataclasses
的项目.它使用不同的继承合并策略;它将子类中被重写的字段拉到字段列表的末尾,因此Parent
类中的['name', 'age', 'ugly']
变为Child
类中的['name', 'age', 'school', 'ugly']
;通过使用默认值覆盖字段,attrs
允许覆盖,而无需执行MRO舞蹈.
attrs
支持定义没有类型提示的字段,但让我们通过设置auto_attribs=True
来坚持supported type hinting mode:
import attr
@attr.s(auto_attribs=True)
class Parent:
name: str
age: int
ugly: bool = False
def print_name(self):
print(self.name)
def print_age(self):
print(self.age)
def print_id(self):
print(f"The Name is {self.name} and {self.name} is {self.age} year old")
@attr.s(auto_attribs=True)
class Child(Parent):
school: str
ugly: bool = True