Skip to main content
 首页 » 编程设计

python 3 : How to use a type defined later for Function Annotations

2025年05月04日8lyhabc

问题是这样的:

class A(): 
    def foo() -> B: 
        pass 
 
class B(): 
    def bar() -> A: 
        pass 

这将引发 NameError: name 'B' is not defined.

所以为了类型检查,我不愿意把->B改成->"B"。那么有什么解决方法吗?


为了进一步讨论,我真的看不出像“def foo(a: 'x', b: 5 + 6, c: list) -> max(2, 9):”这样的注释有任何意义(在 PEP 3107 中)。为什么 python 会威胁这些注释来表达?

请您参考如下方法:

您可以将第一个引用作为字符串传递(Python 3.5+):

class A(): 
    def foo() -> 'B': 
        pass 
 
class B(): 
    def bar() -> A: 
        pass 
 

它被称为“前向引用”并在 PEP484 中列出。 .参见 this answer获取更多方式和详细信息。希望这可以帮助任何人通过谷歌找到它。