Pythonプロパティを使用して、各フィールドに個別にルールをクリーンに適用し、クライアントコードがフィールドを変更しようとした場合でもルールを適用できます。
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__関数内であっても、ルールに違反しようとすると例外がスローされます。その場合、オブジェクトの構築は失敗します。
更新: 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