gpt4 book ai didi

python-3.x - 如何在 Python 3.7 中验证输入属性

转载 作者:行者123 更新时间:2023-12-04 01:53:49 24 4
gpt4 key购买 nike

我想从实例创建开始验证类型是对还是错,
我尝试使用 @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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com