首页 > 解决方案 > 如何注释可选的类变量

问题描述

在 Python 3 中,如何为可能存在或不存在的类变量添加类型注释。这与可能是的类变量不同None。例如:

from typing import Optional

class Foo:
  a: Optional[int]
  # b: ???

  def __init__(self, has_a: bool, has_b: bool):
    if has_a:
      self.a = 1
    else
      self.a = None

    if has_b:
      self.b = 2

然后

>>> x = Foo(False, False)
>>> repr(x.a)
'None'
>>> repr(x.b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'b'

我要写什么???来指示类型检查器b可能int存在或根本不存在?

标签: pythonannotationstype-hintingpython-typing

解决方案


推荐阅读