我想从实例创建开始验证类型是对还是错,
我尝试使用 @dataclass
装饰器但不允许我使用 __init__
方法,我也尝试使用自定义类类型
还按照类型的顺序进行了一些验证(例如,如果是 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)
关于python-3.x - 如何在 Python 3.7 中验证输入属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51736938/