Python 3.7数据类中的类继承 - python

我目前正在尝试Python 3.7中引入的新数据类构造。我目前坚持尝试做一些父类的继承。看来参数的顺序已被我当前的方法所破坏,因此子类中的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

我该如何解决?

参考方案

数据类组合属性的方式使您无法在基类中使用具有默认值的属性,然后在子类中使用没有默认值的属性(位置属性)。

这是因为通过从MRO的底部开始并按先见顺序建立属性的有序列表来组合属性。替代项将保留在其原始位置。因此,Parent['name', 'age', 'ugly']开始,其中ugly为默认值,然后Child['school']添加到该列表的末尾(列表中已经有ugly)。这意味着您以['name', 'age', 'ugly', 'school']结尾,并且由于school没有默认值,因此会导致__init__的参数列表无效。

这记录在PEP-557 Dataclasses下的inheritance中:

@dataclass装饰器创建数据类时,它将以反向MRO(即,从object开始)浏览该类的所有基类,并为找到的每个数据类添加以下字段:该基类到字段的有序映射。添加所有基类字段后,它将自己的字段添加到有序映射中。所有生成的方法都将使用此组合的,经过计算的字段有序映射。由于字段按插入顺序排列,因此派生类将覆盖基类。

并在Specification下:

如果没有默认值的字段跟随具有默认值的字段,则会引发TypeError。当这发生在单个类中或作为类继承的结果时,都是如此。

您确实有一些选择可以避免此问题。

第一种选择是使用单独的基类将具有默认值的字段强制放入MRO顺序的更高位置。不惜一切代价,避免直接在要用作基类的类上设置字段,例如Parent

以下类层次结构有效:

# 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

通过将字段拉到具有默认值的字段和具有默认值的字段以及精心选择的继承顺序的单独的基类中,可以生成MRO,将所有没有默认值的字段放在具有默认值的字段之前。 object的反向MRO(忽略Child)为:

_ParentBase
_ChildBase
_ParentDefaultsBase
_ChildDefaultsBase
Parent

请注意,Parent不会设置任何新字段,因此此处以字段列出顺序中的“最后一个”结束并不重要。具有默认值(_ParentBase_ChildBase)的字段的类优先于具有默认值(_ParentDefaultsBase_ChildDefaultsBase)的字段的类。

结果是ParentChild类具有更合理的字段,而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)

另一种选择是仅使用具有默认值的字段。您仍然可以通过在school中加1来提供一个不提供__post_init__值的错误:

_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>

类型提示检查器将抱怨不是字符串。

您还可以使用_no_default project,它是启发attrs的项目。它使用不同的继承合并策略。它将子类中的重写字段拉到字段列表的末尾,因此dataclasses类中的['name', 'age', 'ugly']变为Parent类中的['name', 'age', 'school', 'ugly'];通过使用默认值覆盖该字段,Child允许覆盖而无需执行MRO跳舞。

attrs支持定义没有类型提示的字段,但是通过设置attrs坚持使用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 pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…