How can I get Python 3.7 new dataclass field types?

前端 未结 3 1131
抹茶落季
抹茶落季 2020-12-18 17:38

Python 3.7 introduces new feature called data classes.

from dataclasses import dataclass

@dataclass
class MyClass:
    id: int = 0
    name: str = \'\'
         


        
3条回答
  •  旧时难觅i
    2020-12-18 18:30

    The dataclasses.py is the module which provides decorator and functions for generating regular class methods by using of the field annotations. Which means that after processing class, the user defined fields shall be formed using PEP 526 Syntax of Variable annotations. The module annotations is accessible as __annotations__.

    According to the Runtime effects of type annotations the annotated types is accessible via __annotations__ attribute or by usage of the typing.get_type_hints, the last one the recommended.

    Please see some code samples below:

    from typing import Dict, ClassVar, get_type_hints
    from dataclasses import dataclass
    
    @dataclass
    class Starship:
        hitpoints: int = 50
    
    
    get_type_hints(Starship) // {'hitpoints': int}
    Starship.__annotations__ // {'hitpoints': int}
    dataclasses.__annotations__ // The annotations of the dataclasses module.
    get_type_hints(get_type_hints)
    

提交回复
热议问题