如何在Python中获取成员的类型注释?

问题描述 投票:1回答:1

请考虑以下代码:

from typing import Optional

class Foo:
    def __init__(self):
        self.baz: Optional[int] = None

如何在代码中发现baz类型为Optional[int]?如果我执行type(Foo().baz),我只会得到None

python typing inspect
1个回答
0
投票

您可以在类主体中定义实例属性类型,如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]}
© www.soinside.com 2019 - 2024. All rights reserved.