Python Dataclass推断的字段
在Python中,是否有可能在数据级别中将其值从数据级别的其他字段中推断出其值?在这种情况下,cachekey
只是其他字段的组合,我不想在对象实例化中明确提及它。
@dataclass
class SampleInput:
uuid: str
date: str
requestType: str
cacheKey = f"{self.uuid}:{self.date}:{self.requestType}" # Expressing the idea
Is it possible in python to have fields in a dataclass which infer their value from other fields in the dataclass? In this case the cacheKey
is just a combination of other fields and I don't want to mention it explicitly in the object instantiation.
@dataclass
class SampleInput:
uuid: str
date: str
requestType: str
cacheKey = f"{self.uuid}:{self.date}:{self.requestType}" # Expressing the idea
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 post_init 使用其他字段:
You can use post_init to use the other fields:
只需在您的班级定义中使用Python属性:
这是最直接的方法。唯一的缺点是,如果您使用诸如
daclasses.asdict
之类的序列化方法,则cachekey
不会显示为类的字段。Just use a Python property in your class definition:
This is the most straightforward approach. The only drawback is that
cacheKey
won't show up as a field of your class if you use serialization methods such asdaclasses.asdict
.