【问题标题】:How to get class variables and type hints?如何获取类变量和类型提示?
【发布时间】:2019-03-21 03:34:08
【问题描述】:

假设我定义了一个带有类型提示的类级别变量的类(例如新的 python 3.7 dataclasses

class Person:
    name: str
    age: int

    def parse_me(self):
        "what do I do here??"        

如何获得(variable name, variable type) 的对?

【问题讨论】:

标签: python type-hinting


【解决方案1】:

这些类型提示基于 Python 注释。它们可作为 __annotations__ 属性使用。这适用于类和函数。

>>> class Person:
...     name: str
...     age: int
... 
>>> Person.__annotations__
{'name': <class 'str'>, 'age': <class 'int'>}
>>> def do(something: str) -> int:
...     ...
... 
>>> do.__annotations__
{'something': <class 'str'>, 'return': <class 'int'>}

【讨论】:

    【解决方案2】:

    typing.get_type_hints 是另一种不涉及直接访问魔法属性的方法:

    from typing import get_type_hints
    
    class Person:
        name: str
        age: int
    
    get_type_hints(Person)
    # returns {'name': <class 'str'>, 'age': <class 'int'>}
    

    【讨论】:

    • 它还呈现以字符串形式给出的“转发”注释。
    猜你喜欢
    • 2011-09-09
    • 2013-09-28
    • 2012-07-03
    • 2016-12-03
    • 1970-01-01
    • 2010-12-21
    • 2014-09-14
    相关资源
    最近更新 更多