【问题标题】:Python typing class type in single quotes [duplicate]Python在单引号中键入类类型[重复]
【发布时间】:2021-12-15 03:49:24
【问题描述】:
class Person:
    def __init__(self, ......  

    def make_friend(self, friend: 'Person') -> None:
        .....

我正在学习 python,但我不明白这个例子。为什么朋友的类型条件应该用单引号引起来?为什么不friend: Person?它是如何工作的?它与类型类快捷方式有什么共同之处吗?

【问题讨论】:

    标签: python oop typing


    【解决方案1】:

    函数make_friend定义在类Person之前。

    创建类时,首先创建命名空间(内部类函数),然后将其构建到类中(使用__prepare__ 方法)。

    在创建之前尝试引用Person 将会失败。

    可以通过“前向引用”来解决它,它可以与引号一起使用,也可以在文件顶部使用from __future__ import annotations

    【讨论】:

      猜你喜欢
      • 2018-07-31
      • 2020-10-14
      • 1970-01-01
      • 2013-09-08
      • 2020-01-26
      • 1970-01-01
      • 2019-07-08
      • 1970-01-01
      • 2016-01-08
      相关资源
      最近更新 更多