如何添加日期时间。现在().isoformat()转换为NamedTuple的?

2024-09-29 06:28:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我当然试过:

class PdfContentRecord(NamedTuple):
    filename: str
    page: int
    cache: dict
    data: dict = dict()
    accessed: str = None

    def __new__(cls, *args, **kwargs):
        self = super().__new__(*args, **kwargs)
        self.accessed = datetime.now().isoformat()
        return self

但是我得到了和How to provide additional initialization for a subclass of namedtuple?完全相同的错误

我不知道attrs是否能帮助我(太难理解了)。dataclasses.dataclass可能有帮助,但它只支持python3.7。在

或者我可以用__slots__编写我的类。。。在

编辑:

Did you read the answer in the question you linked?

from collection import namedtuple一起工作,但不与{}一起使用。在


Tags: theselfyounewpageargsfilenamenamedtuple
2条回答

python3.7+用户应该只利用^{}^{}中的^{}钩子。对于使用旧版Python的用户,请继续阅读。。在

我认为你应该可以用一层额外的类型来完成:

from datetime import datetime
from typing import NamedTuple


class _PdfContentRecord(NamedTuple):
    filename: str
    page: int
    cache: dict
    data: dict = None
    accessed: str = None


class PdfContentRecord(_PdfContentRecord):

    def __new__(cls, filename, page, cache, data=None, accessed=None):
        if data is None:
            data = {}
        if accessed is None:
            accessed = datetime.now().isoformat()
        return super().__new__(cls, filename, page, cache, data, accessed)

不过,可以说,您首先失去了使用NamedTuple的一些好处,而且还可以自己编写子类型。在

一个非常漂亮的答案,需要pip install attrs(这激发了dataclass

import attr

@attr.s
class PdfFileRecord:
    name: str = attr.ib()
    type: str = attr.ib()
    cache: dict = attr.ib()
    data: dict = attr.ib(factory=dict)
    accessed: str = attr.ib(factory =lambda: datetime.now().isoformat())

对于^{}版本,不需要pip,而是at least Python 3.6 is needed。在

^{pr2}$

相关问题 更多 >