python-3.x - 如何在 Python 3.7 中验证类型属性
问题描述
我想验证实例创建以来类型是对还是错,我尝试使用@dataclass
装饰器但不允许我使用该__init__
方法,我还尝试使用自定义类类型
还按照类型的顺序进行了一些验证(例如,如果是 a int
,field>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
解决方案
您可以使用数据类的__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)
推荐阅读
- javascript - 401 Unauthorized, SyntaxError: JSON.parse: 意外字符在 JSON 数据的第 1 行第 1 列
- python - 如何删除具有空值的字典键?
- laravel - 带有大量参数的可选查询
- python - 谷歌浏览器无法读取和写入其数据目录:selenium
- powerbi - 如何在 PowerBI 中将报告下载为 Excel
- postgresql - 如何将 NOT LIKE 与查询结果一起用作模式
- azure-devops - 使用 sonarqube 时 Azure devops 构建卡在队列中
- html - div和父div边框之间的空白
- javascript - 有反应 redux 调度计划吗?
- ruby - Nokogiri 和 Open-Uri 的警告消息