使用PEP 557,数据类被引入到python标准库中.
他们使用@dataclass装饰器,他们应该是"默认的可变的命名元组",但我不确定我理解这实际意味着什么,以及它们与普通类的区别.
究竟什么是python数据类以及何时最好使用它们?
我有以下命名的元组:
from collections import namedtuple
ReadElement = namedtuple('ReadElement', 'address value')
Run Code Online (Sandbox Code Playgroud)
然后我想要以下内容:
LookupElement = namedtuple('LookupElement', 'address value lookups')
Run Code Online (Sandbox Code Playgroud)
两个命名元组之间存在重复,如何将ReadElement子类化为包含其他字段?
class LookupElement(ReadElement):
def __new__(self, address, value, lookups):
self = super(LookupElement, self).__new__(address, value)
l = list(self)
l.append(lookups)
return tuple(l)
Run Code Online (Sandbox Code Playgroud)
然而,在新语句中创建了元组,如果我将self修改为列表,我将丢失类型信息,我该如何避免这种情况?
假设我想存储一些有关会议日程的信息,包括演示时间和暂停时间。我可以在NamedTuple.
from typing import NamedTuple
class BlockTime(NamedTuple):
t_present: float
t_pause: float
Run Code Online (Sandbox Code Playgroud)
但是,如果我还想存储每个块将占用多少t_each = t_pause + t_present,我不能只将其添加为属性:
class BlockTime(NamedTuple):
t_present: float
t_pause: float
# this causes an error
t_each = t_present + t_pause
Run Code Online (Sandbox Code Playgroud)
在 Python 中执行此操作的正确方法是什么?如果我创建一个__init__(self)方法并将其作为实例变量存储在那里,但它是可变的。