当实例化 class 时,在 dataclass 中创建时间戳

Create timestamp inside of dataclass when class is instantiated

我正在使用数据class,我想在每次创建 class 的实例时创建一个时间戳,如下所示:

@dataclass
class test:
    timestamp: datetime = datetime.utcnow()

test1 = test()

但是,这样做会产生一个时间戳,截至我 运行 原始 class 对象的代码时。也就是说,新实例都具有相同的时间戳。

下面的方法可以满足我的要求,但我不明白为什么。我认为上述方法也应该有效,因为没有创建 class 的实例。为什么我必须用那个领域的方法来写它?

@dataclass
class test:
timestamp: datetime = field(default_factory=datetime.utcnow)

test1 = test()
test1.timestamp

dataclasses.field 的文档对此进行了解释:

…some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided field() function.
. . .
If the default value of a field is specified by a call to field(), then the class attribute for this field will be replaced by the specified default value. If no default is provided, then the class attribute will be deleted. The intent is that after the dataclass() decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified.

在第一种情况下,在定义 class 时计算 datetime.utcnow()。这有效地为该字段提供了默认值。当您创建 class 的对象时,不会再次执行该评估 - 因此您只剩下与您创建的 class.

的所有实例共享的单个值

另一方面,default_factory 使用可调用对象,每当创建 class 的新实例时都会调用该调用对象 - 并且该调用的结果用于填充该字段。因此,当您创建 test class 的对象时,datetime.utcnow() 再次运行并且该实例中存在更新的时间戳。

阅读 docs 了解更多信息。