我目前正在尝试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
)的字段的类。
结果是Parent
和Child
类具有更合理的字段,而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'")
但这确实改变了场序; school
在ugly
之后结束:
<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抑制异常 - pythonfrom 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…