python - 如何注释可选的类变量
问题描述
在 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
存在或根本不存在?
解决方案
推荐阅读
- vue.js - 如何引用组件中的子元素?
- c++ - 编译器错误 boost::asio::placeholder::error with boost v1.69
- unicode - 抓取法国网站并获取 UnicodeEncodeError
- java - ESAPI 未通过文件验证
- css-filters - 为什么 CSS 过滤器不影响 html 元素的背景图片?
- python - Python Tkinter:如何用一个按钮更改两个字符串变量,中间有延迟?
- spring-boot - 在 Web 应用程序之外使用 Spring Boot 中的实体和存储库定义
- ms-access - MS Access:导航表单子表单中的查询条件
- racket - 一个数字的递归,如果它在 Racket 中按升序排列而不使用列表
- mysql - MySQL获取每个加入多列的组的最大值