- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑以下两种情况:
from queue import Queue
my_q: Queue[int] = Queue()
print(f"queue={my_q}")
和
from queue import Queue
class MyClass(object):
def __init__(self):
self.my_q: Queue[int] = Queue()
my_class = MyClass()
print(f"queue={my_class.my_q}")
运行前者(预期)会抛出
TypeError
:
$ python3 run.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
my_q: Queue[int] = Queue()
TypeError: 'type' object is not subscriptable
然而后者没有,并且没有问题地继续打印语句:
$ python3 run.py
queue=<queue.Queue object at 0x7fb40265f730>
我希望
TypeError
在这两种情况下。为什么没有
TypeError
当
Queue[int]
类型在类的
__init__
内方法?
最佳答案
模块和类注释都可以在运行时访问,因此可以评估:
# example.py
a: int = 4
print(__annotations__) # {'a': <class 'int'>}
相反,函数的本地注释是不可访问的,因此永远不会被评估。
Once compiled, a function's annotations are available via the function's
__annotations__
attribute.
In addition, at the module or class level, if the item being annotated is a simple name, then it and the annotation will be stored in the
__annotations__
attribute of that module or class (mangled if private) as an ordered mapping from names to evaluated annotations.
[...]
Also the value of having annotations available locally does not offset the cost of having to create and populate the annotations dictionary on every function call. Therefore, annotations at function level are not evaluated and not stored.
Note that as per PEP 526, local variable annotations are not evaluated at all since they are not accessible outside of the function's closure.
关于python - 非泛型类型的不同运行时行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66859447/
我是一名优秀的程序员,十分优秀!