我目前正在try Python 3.7中引入的新数据类构造.我目前一直在try 继承父类.我目前的方法似乎弄糟了参数的顺序,使得子类中的bool参数在其他参数之前被传递.这会导致类型错误.

from dataclasses import dataclass

@dataclass
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')

@dataclass
class Child(Parent):
    school: str
    ugly: bool = True


jack = Parent('jack snr', 32, ugly=True)
jack_son = Child('jack jnr', 12, school = 'havard', ugly=True)

jack.print_id()
jack_son.print_id()

当我运行这段代码时,我得到TypeError:

TypeError: non-default argument 'school' follows default argument

我该怎么解决这个问题?

推荐答案

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)之前.

结果是ParentChild个类,其中一个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'")

但这改变了场秩序;schoolugly之后结束:

<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

Python-3.x相关问答推荐

当条件第一次出现时将行标记为True,如果按顺序重复则标记为False

Select 作为 MultiIndex 一部分的两个 DatetimeIndex 之间的行

Django中自动设置/更新字段

通过匹配第一列的行值,逐个单元格地添加两个Pandas 数据框中的浮点数

以不规则频率识别数据框日期时间列上缺失的日期,并用关联值填充它们

Pandas 在每组两个条件之间获得时间增量

删除给定数组中所有元素为True的所有子数组

从日志(log)文件中查找延迟最低的用户

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

如何判断一个字符串是否包含有效的 Python 代码

Linux Mint 上的 Python3 错误没有名为蓝牙的模块

如何配置 Atom 以运行 Python3 脚本?

如何将numpy数组图像转换为字节?

如何模拟 open(...).write() 而不会出现没有这样的文件或目录错误?

尾部斜杠的 FastAPI 重定向返回非 ssl 链接

有效地判断一个元素是否在列表中至少出现 n 次

如何开始使用 PyWin32

@staticmethod 或类外的函数?

update和update_idletasks有什么区别?