Python:如何从数据类中获取属性及其类型?

时间:2021-03-05 20:26:53

标签: python oop python-dataclasses

我想从(数据)类中读取所有属性及其类型,如此所需的(伪)代码所示:

from dataclasses import dataclass


@dataclass
class HelloWorld:
    name: str = 'Earth'
    is_planet: bool = True
    radius: int = 6371


if __name__ == '__main__':
    attrs = get_attributes(HelloWorld)
    for attr in attrs:
        print(attr.name, attr.type)  # name, str

我检查了几个 answers,但还没有找到我需要的。

有什么想法吗?提前致谢!

2 个答案:

答案 0 :(得分:1)

看看这个:

from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

Point.__annotations__ 返回 {'x': <class 'int'>, 'y': <class 'int'>}

答案 1 :(得分:1)

对于一般的类,您可以访问 __annotations__

>>> class Foo:
...    bar: int
...    baz: str
...
>>> Foo.__annotations__
{'bar': <class 'int'>, 'baz': <class 'str'>}

这会返回一个 dict 映射属性名称到注释。

然而,数据类已经使用 dataclass.field 对象来封装大量此类信息。您可以在实例或类上使用 dataclasses.fields

>>> import dataclasses
>>> @dataclasses.dataclass
... class Foo:
...     bar: int
...     baz: str
...
>>> dataclasses.fields(Foo)
(Field(name='bar',type=<class 'int'>,default=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD), Field(name='baz',type=<class 'str'>,default=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD))

注意:

Starting in Python 3.7, the evaluation of annotations can be postponed

>>> from __future__ import annotations
>>> class Foo:
...     bar: int
...     baz: str
...
>>> Foo.__annotations__
{'bar': 'int', 'baz': 'str'} 

注意,注释保留为字符串,这也会影响dataclasses

>>> @dataclasses.dataclass
... class Foo:
...     bar: int
...     baz: str
...
>>> dataclasses.fields(Foo)
(Field(name='bar',type='int',default=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD), Field(name='baz',type='str',default=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,default_factory=<dataclasses._MISSING_TYPE object at 0x7f806369bc10>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD))

因此,请注意,由于这将成为标准行为,您编写的代码可能应该使用 __future__ 导入并在该假设下工作,因为在 Python 3.10 中,这将成为标准行为。

这种行为背后的动机是以下当前会引发错误:

>>> class Node:
...    def foo(self) -> Node:
...        return Node()
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in Node
NameError: name 'Node' is not defined

但是有了新的行为:

>>> from __future__ import annotations
>>> class Node:
...     def foo(self) -> Node:
...         return Node()
...
>>>

处理这个问题的一种方法是使用 typing.get_type_hints,我相信它基本上就是 eval 的类型提示:

>>> import typing
>>> typing.get_type_hints(Node.foo)
{'return': <class '__main__.Node'>}
>>> class Foo:
...    bar: int
...    baz: str
...
>>> Foo.__annotations__
{'bar': 'int', 'baz': 'str'}
>>> import typing
>>> typing.get_type_hints(Foo)
{'bar': <class 'int'>, 'baz': <class 'str'>}

不确定这个函数有多可靠,但基本上,它处理获取定义类的位置的适当 globalslocals。因此,请考虑:

(py38) juanarrivillaga@Juan-Arrivillaga-MacBook-Pro ~ % cat test.py
from __future__ import annotations

import typing

class Node:
    next: Node

(py38) juanarrivillaga@Juan-Arrivillaga-MacBook-Pro ~ % python
Python 3.8.5 (default, Sep  4 2020, 02:22:02)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.Node
<class 'test.Node'>
>>> import typing
>>> typing.get_type_hints(test.Node)
{'next': <class 'test.Node'>}

天真地,您可能会尝试以下操作:

>>> test.Node.__annotations__
{'next': 'Node'}
>>> eval(test.Node.__annotations__['next'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'Node' is not defined

你可以像这样一起破解:

>>> eval(test.Node.__annotations__['next'], vars(test))
<class 'test.Node'>

但它可能会变得棘手