[英]How to annotate a dataclass' attribute as another dataclass' object?
I have two dataclasses like:我有两个数据类,如:
from dataclasses import dataclass
from pathlib import Path
@dataclass
class InnerDataClass:
host: str
@dataclass
class OuterDataClass:
directory: Path
host: InnerDataClass
When I call OuterDataClass(...)
, Python returns the error NameError: name 'InnerDataClass' is not defined
on the last line.当我调用
OuterDataClass(...)
,Python 返回错误NameError: name 'InnerDataClass' is not defined
在最后一行。 Why does it do this and how can I resolve it?为什么会这样,我该如何解决?
Your example actually works, you probably had the order of classes the other way round in your actual code.您的示例确实有效,您的实际代码中可能有相反的类顺序。 Python code files get executed line by line, so when the first classe's class body is executed, the second class needs to exist already.
Python 代码文件是逐行执行的,所以当第一个类的类体被执行时,第二个类需要已经存在。 You have to declare classes in the order that matches their internal hierarchy from bottom to top if you want things to work.
如果你想让事情正常工作,你必须按照与它们的内部层次结构相匹配的顺序从下到上声明类。
But if all you're doing is annotating and not actual instance creation, you can also do this:但是,如果您所做的只是注释而不是实际创建实例,您也可以这样做:
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
@dataclass
class OuterDataClass:
directory: Path
host: InnerDataClass
@dataclass
class InnerDataClass:
host: str
Running from __future__ import annotations
as the first line of your code file will make annotations work, no matter the order classes were defined in. It was introduced as PEP 563 to help, among other things, with circular dependencies.运行
from __future__ import annotations
作为代码文件的第一行将使注释工作,无论类的定义顺序如何。它作为PEP 563引入,以帮助解决循环依赖等问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.