验证类实例的属性的正确方法 [英] Correct approach to validate attributes of an instance of class
问题描述
拥有一个简单的Python类:
Having a simple Python class like this:
class Spam(object):
__init__(self, description, value):
self.description = description
self.value = value
我想检查以下限制:
- 描述不能为空
- 值必须大于零
我应该:
1.创建垃圾邮件对象之前验证数据? br>
2.检查 __ init __
方法上的数据?
3.创建一个 is_valid
方法在垃圾邮件类,并用spam.isValid()?调用?
4.在垃圾邮件类上创建一个 is_valid
静态方法,并将其调用Spam.isValid(描述,价值)?
5.检查设定者声明的数据?
6.等
Should I:
1. validate data before creating spam object ?
2. check data on __init__
method ?
3. create an is_valid
method on Spam class and call it with spam.isValid() ?
4. create an is_valid
static method on Spam class and call it with Spam.isValid(description, value) ?
5. check data on setters declaration ?
6. etc.
你可以推荐一个精心设计的/ Pythonic /不是冗长的(在类上有许多属性)/优雅的方法?
Could you recommend a well designed/Pythonic/not verbose (on class with many attributes)/elegant approach?
推荐答案
您可以使用Python 属性清理适用规则分配到每个字段,并执行它们,即使客户端代码尝试更改字段:
You can use Python properties to cleanly apply rules to each field separately, and enforce them even when client code tries to change the field:
class Spam(object):
def __init__(self, description, value):
self.description = description
self.value = value
@property
def description(self):
return self._description
@description.setter
def description(self, d):
if not d: raise Exception("description cannot be empty")
self._description = d
@property
def value(self):
return self._value
@value.setter
def value(self, v):
if not (v > 0): raise Exception("value must be greater than zero")
self._value = v
即使在 __ init __
函数中,任何违反规则的尝试都将抛出异常,在这种情况下,对象构造将失败。
An exception will be thrown on any attempt to violate the rules, even in the __init__
function, in which case object construction will fail.
更新:在2010年和现在之间的某个时间,我了解了 operator.attrgetter
:
UPDATE: Sometime between 2010 and now, I learned about operator.attrgetter
:
import operator
class Spam(object):
def __init__(self, description, value):
self.description = description
self.value = value
description = property(operator.attrgetter('_description'))
@description.setter
def description(self, d):
if not d: raise Exception("description cannot be empty")
self._description = d
value = property(operator.attrgetter('_value'))
@value.setter
def value(self, v):
if not (v > 0): raise Exception("value must be greater than zero")
self._value = v
这篇关于验证类实例的属性的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!