有一个像这样的简单 Python 类:
class Spam(object):
__init__(self, description, value):
self.description = description
self.value = value
我想检查以下限制:
我是不是该:
1. 在创建垃圾邮件对象之前验证数据 ?
2.检查数据__init__
方法 ?
3. 创建一个is_valid
Spam 类上的方法并使用 spam.isValid() 调用它?
4. 创建一个is_valid
Spam 类上的静态方法并使用 Spam.isValid(description, value) 调用它?
5.检查设置者声明的数据?
6. 等等
您能否推荐一种设计良好/Pythonic/不冗长(在具有许多属性的类上)/优雅的方法?
你可以使用Python特性 http://docs.python.org/library/functions.html#property干净地分别将规则应用于每个字段,并在客户端代码尝试更改该字段时强制执行它们:
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__
函数,在这种情况下对象构造将会失败。
UPDATE:从 2010 年至今,我了解到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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)