python - 将属性添加到 Python TypedDict
问题描述
我想在我的TypedDict
对象中有一个别名,以免我在运行时进行许多 if/else 检查(TypedDict
在数据加载期间创建)。
我有这样的事情:
class PatientJson(TypedDict):
id: int
name: str
我想将user_id
别名添加到PatientJson
,这将返回id
。这将使列表推导总是指向user_id
而不是检查哪个 ID 存在。
但是,使用此代码:
class PatientJson(TypedDict):
id: int
name: str
@property
def user_id(self) -> int
return self.id
我得到一个错误Invalid statement in TypedDict definition; expected 'field_name: field_type'
。我发现 TypedDicts 不能有方法(链接 1,链接 2)。这也会改变语法,因为我必须使用patient.user_id
而不是,patient["user_id"]
这将是很多代码更改。我怎样才能做到这一点?如果可能,我想避免添加冗余字段。
解决方案
推荐阅读
- spring - Spring Batch 集成 - 如何获取远程执行 JVM 上 StepLocator 可见的作业外部的远程步骤?
- android - 如何在从 Firestore 数据库中获取的 cardview recyclerview 上添加 onclick 侦听器
- ionic-framework - 离子发布 apk 每次构建都会增加文件大小
- jquery - 如何在不加载以前加载的帖子的情况下在新闻提要中加载更多帖子?
- ruby-on-rails - webpack编译失败时如何发送错误500?
- r - 提取匹配内容并合并它们
- javafx - 当我使用 javafx 连接到数据库时遇到问题
- javascript - JavaScript作业问题中的自定义排序
- node.js - VSCode 任务错误:/bin/bash: npm: command not found
- c++ - 从包含 unordered_maps 的 unordered_map 中提取信息