擅长:python、mysql、java
<p>另一种方法是,用一个可配置的验证器作为装饰器,您可以在几个不同的子类和基类上使用,这样可以节省一些冗长的内容。
基类使用类型注释声明属性</p>
<pre><code>def validate_with(baseclass):
def validator(cls):
for n, t in baseclass.__annotations__.items():
if not isinstance(getattr(cls, n), t):
raise ValueError(f"{n} is not of type {t}!!!")
return cls
return validator
class BaseClass:
s: str
i: int
@validate_with(BaseClass)
class SubClass(BaseClass):
i = 3
s = 'xyz'
</code></pre>
<p>如果类型不匹配,则引发<code>ValueError</code>;如果属性不存在,则引发<code>AttributeError</code>。你知道吗</p>
<p>当然,您可以收集错误(如前一个答案所示)并一次性地将它们全部呈现出来,而不是在第一个错误时停止</p>