[英]How to get type annotations for class members?
Consider the following code:考虑以下代码:
from typing import Optional
class Foo:
def __init__(self):
self.baz: Optional[int] = None
How do I find in code that baz has type Optional[int]
?如何在代码中找到 baz 的类型为Optional[int]
? If I do type(Foo().baz)
, I only get None
.如果我type(Foo().baz)
,我只会得到None
。
You could define the instance attribute type in the class body, as described in the PEP您可以在类主体中定义实例属性类型,如PEP中所述
from typing import Optional, get_type_hints
class Foo:
baz: Optional[int]
def __init__(self):
self.baz = None
get_type_hints(Foo)
Out[26]: {'baz': typing.Union[int, NoneType]}
Note that typing.Union[int, NoneType]
is the same as Optional[int]
.请注意, typing.Union[int, NoneType]
与Optional[int]
相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.