数据类不实例化变量
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要一个实例属性,而不是类属性,它可以初始化到当前时间。使用
dataclasses.field
将类配置以使用默认工厂来定义ts
字段,如果实例化没有明确值。然后,您可以使用默认值
或提供明确的时间戳(如果没有其他)
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 thets
field if no explicit value is given on instantiation.Then you can use the default
or provide an explicit timestamp (for testing, if nothing else)