如何在 Python 3.7 中验证类型属性

Car*_*jas 5 oop python-3.x python-3.7

我想在实例创建后验证类型是否正确,我尝试使用@dataclass装饰器,但不允许我使用该__init__方法,我还尝试使用自定义类类型

还按照类型的顺序进行了一些验证(例如,如果是 a int,则field>0或者 if 是str干净的空格),我可以使用字典来验证类型,但我想知道是否有办法在 pythonic 中做到这一点方式

class Car(object):
    """ My class with many fields """

    color: str
    name: str
    wheels: int

    def __init__(self):
        """ Get the type of fields and validate """
        pass
Run Code Online (Sandbox Code Playgroud)

Pat*_*ugh 8

您可以使用__post_init__数据类的方法来进行验证。

下面我只是确认一切都是指定类型的实例

from dataclasses import dataclass, fields

def validate(instance):
    for field in fields(instance):
        attr = getattr(instance, field.name)
        if not isinstance(attr, field.type):
            msg = "Field {0.name} is of type {1}, should be {0.type}".format(field, type(attr))
            raise ValueError(msg)

@dataclass
class Car:
    color:  str
    name:   str
    wheels: int    
    def __post_init__(self):
        validate(self)
Run Code Online (Sandbox Code Playgroud)