Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将属性添加到Python TypedDict_Python_Json_Python Typing - Fatal编程技术网

将属性添加到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。