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

标签 python-3.x oop python-3.7

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

相关文章:

python - 如何使用 Python 3.3 和 Qt 5 构建 GUI 应用程序?

python - 错误 : sqlite3. 操作错误 : no such table: main. m

perl - 我应该使用继承还是组合?

asp.net-mvc - 如何构建通用存储库

python - 如何为 __getitem__() 调用执行 assert_has_calls?

python-3.x - Python3 - 无法在 "import cairosvg"上加载库

Python:字符串格式化程序以获得带下划线的标题

python - 如何使用 Python 创建 JSON 对象的嵌套数组?

python - 在很多类 : DRY? 上定义相同的方法覆盖

oop - 面向对象的指标?