首页 > 解决方案 > 将属性添加到 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"]这将是很多代码更改。我怎样才能做到这一点?如果可能,我想避免添加冗余字段。

标签: pythonjsonpython-typing

解决方案


推荐阅读