将属性添加到Python TypedDict
我希望在我的将属性添加到Python TypedDict,python,json,python-typing,Python,Json,Python Typing,我希望在我的TypedDict对象中有一个别名,以避免在运行时执行许多if/else检查(TypedDict是在数据加载期间创建的) 我有这样的想法: class PatientJson(TypedDict): id: int name: str 我想将user\u id别名添加到PatientJson,它将返回id。这将使列表理解始终指向user\u id,而不是检查哪个id存在 但是,使用此代码: class PatientJson(TypedDict): id:
TypedDict
对象中有一个别名,以避免在运行时执行许多if/else检查(TypedDict
是在数据加载期间创建的)
我有这样的想法:
class PatientJson(TypedDict):
id: int
name: str
我想将user\u id
别名添加到PatientJson
,它将返回id
。这将使列表理解始终指向user\u id
,而不是检查哪个id存在
但是,使用此代码:
class PatientJson(TypedDict):
id: int
name: str
@property
def user_id(self) -> int
return self.id
我在TypedDict定义中得到一个错误
无效语句;应为“字段名称:字段类型”
。我发现TypedDicts不能有方法(,)。这也会改变语法,因为我将不得不使用patient.user\u id
而不是patient[“user\u id”]
,这将是大量的代码更改。我该怎么做?如果可能的话,我希望避免添加冗余字段。我在运行您的代码时没有问题。@Johnny它可能会工作,但我必须使用基于点的语法来调用patient.user\u id,而不是patient[“user\u id”]。这需要对代码进行大量更改。我想改用常规的dict访问,比如常规的TypedDict。