数据类不实例化变量

发布于 2025-02-04 17:50:32 字数 231 浏览 4 评论 0原文

import time
from dataclasses import dataclass


@dataclass
class Test:

    ts=time.time()


while 1:
    m = Test()
    print(m.ts)
    time.sleep(2)

有了这个代码,我希望每次都会增加2个时间,但是它保持不变。每次实例化数据级时,我如何有时间刷新?

import time
from dataclasses import dataclass


@dataclass
class Test:

    ts=time.time()


while 1:
    m = Test()
    print(m.ts)
    time.sleep(2)

With this code, I would expect the time to be increasing by 2 every time, but it is staying constant. How can I get the time to refresh everytime the dataclass is instantiated?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小镇女孩 2025-02-11 17:50:32

您需要一个实例属性,而不是类属性,它可以初始化到当前时间。使用dataclasses.field将类配置以使用默认工厂来定义ts字段,如果实例化没有明确值。

from dataclasses import dataclass, field
import time


@dataclass
class Test:
    ts: float = field(default_factory=time.time)

然后,您可以使用默认值

>>> Test().ts
1654541245.673183

或提供明确的时间戳(如果没有其他)

>>> Test(3.14159).ts
3.14159

You want an instance attribute, not a class attribute, that gets initialized to the current time. Use dataclasses.field to configure the class to use a default factory to define the ts field if no explicit value is given on instantiation.

from dataclasses import dataclass, field
import time


@dataclass
class Test:
    ts: float = field(default_factory=time.time)

Then you can use the default

>>> Test().ts
1654541245.673183

or provide an explicit timestamp (for testing, if nothing else)

>>> Test(3.14159).ts
3.14159
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文