qal*_*lis 5 python json python-typing
我希望在我的TypedDict对象中有一个别名,以便在运行时期间避免许多 if/else 检查(TypedDict在数据加载期间创建)。
我有这样的事情:
class PatientJson(TypedDict):
id: int
name: str
Run Code Online (Sandbox Code Playgroud)
我想添加user_id别名PatientJson,这将返回id. 这将使列表推导始终指向user_id而不是检查哪个 ID 存在。
但是,使用这段代码:
class PatientJson(TypedDict):
id: int
name: str
@property
def user_id(self) -> int
return self.id
Run Code Online (Sandbox Code Playgroud)
我收到一个错误Invalid statement in TypedDict definition; expected 'field_name: field_type'。我发现 TypedDicts 不能有方法(链接 1,链接 2)。这也会改变语法,因为我必须使用patient.user_id而不是patient["user_id"],这将是很多代码更改。我怎样才能做到这一点?如果可能的话,我想避免添加冗余字段。
小智 1
对于常规的typing.TypedDict,这是不可能的。允许通过访问某些内容的典型方法obj[key]是实现__getitem__,但是TypedDict 对象的运行时类型将始终是 justdict,因此您无法覆盖__getitem__.