我想在Python中编写一个数据类定义,但无法在声明内部引用同一类。
主要想要实现的是嵌套结构的类型注释,如下所示:
@dataclass
class Category:
title: str
children: [Category] # I can't refer to a "Category"
tree = Category(title='title 1', children=[
Category('title 11', children=[]),
Category('title 12', children=[])
])
__future__
导入才能启用。 - Blckknghtannotations
的缺点是:它会使本来合法的代码因为NameError: name 'Sub' is not defined
而失败:from __future__ import annotations # 如果注释掉这行就可以正常运行 import dataclasses from dataclasses import dataclass from dataclasses_serialization.json import JSONSerializer def test1(): # 如果将此函数移到模块级别,就可以正常运行 @dataclass class Sub: x: int @dataclass class Foo: s: Sub=None a=Foo(s=Sub(x=1)) j=JSONSerializer.serialize(a) a2=JSONSerializer.deserialize(Foo, j) test1()
- timotheecourglobals().update(locals())
,它基本上只是更新了模块级别的全局值与函数(或测试用例)级别定义的任何类,直到那个点为止。 - rv.kvetch