首页 > 解决方案 > 如何在 Python 3.7 中验证类型属性

问题描述

我想验证实例创建以来类型是对还是错,我尝试使用@dataclass装饰器但不允许我使用该__init__方法,我还尝试使用自定义类类型

还按照类型的顺序进行了一些验证(例如,如果是 a intfield>0或者如果是str干净的空格),我可以使用 dict 来验证类型,但我想知道是否有办法在 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

标签: python-3.xooppython-3.7

解决方案


您可以使用数据类的__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)

推荐阅读