我希望在我的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不能有方法(link 1,link 2)。这也会改变语法,因为我将不得不使用patient.user_id
而不是patient["user_id"]
,这将是大量的代码更改。我该怎么做?我希望尽可能避免添加冗余字段
目前没有回答
相关问题 更多 >
编程相关推荐