Python Dataclass推断的字段

发布于 2025-02-14 01:58:35 字数 278 浏览 4 评论 0原文

在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 技术交流群。

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

发布评论

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

评论(2

徒留西风 2025-02-21 01:58:35

您可以使用 post_init 使用其他字段:

@dataclass
class SampleInput:
   uuid: str
   date: str
   requestType: str

   def __post_init__(self):
        self.cacheKey = f"{self.uuid}:{self.date}:{self.requestType}" 

You can use post_init to use the other fields:

@dataclass
class SampleInput:
   uuid: str
   date: str
   requestType: str

   def __post_init__(self):
        self.cacheKey = f"{self.uuid}:{self.date}:{self.requestType}" 
九厘米的零° 2025-02-21 01:58:35

只需在您的班级定义中使用Python属性:

from dataclasses import dataclass

@dataclass
class SampleInput:
    uuid: str
    date: str
    requestType: str

    @property
    def cacheKey(self):
        return f"{self.uuid}:{self.date}:{self.requestType}"

这是最直接的方法。唯一的缺点是,如果您使用诸如daclasses.asdict之类的序列化方法,则cachekey不会显示为类的字段。

Just use a Python property in your class definition:

from dataclasses import dataclass

@dataclass
class SampleInput:
    uuid: str
    date: str
    requestType: str

    @property
    def cacheKey(self):
        return f"{self.uuid}:{self.date}:{self.requestType}"

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 as daclasses.asdict.

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