如何获取 class 变量和类型提示?
How to get class variables and type hints?
假设我用 class 级别变量定义了一个 class 类型提示(例如像新的 python 3.7 dataclasses
)
class Person:
name: str
age: int
def parse_me(self):
"what do I do here??"
如何获得 (variable name, variable type)
对?
这些类型提示基于 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'>}
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'>}
假设我用 class 级别变量定义了一个 class 类型提示(例如像新的 python 3.7 dataclasses
)
class Person:
name: str
age: int
def parse_me(self):
"what do I do here??"
如何获得 (variable name, variable type)
对?
这些类型提示基于 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'>}
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'>}