Thanks for all of the comments! The general theme of "don't use a
property unless you need to" is intuitive, and is what I was hoping
the consensus would be.
This raised another design issue for me, tho', regarding property
validation. In C#/Java, I would typically do validation in all of my
setter methods, but is this really pythonic? It seems OO--
encapsulation-- but also seems to be one of the biggest wastes of
coding time & typing in those languages.
As a simple example, consider the following class:
# Example: mixing instance attributes with properties. Is it pythonic to
# validate property data in setters? Note that tens and ones are never
# validated, so the class can break by setting these directly...
class SillyDecimal(object):
def __init__(self, arg=17):
if isinstance(arg, tuple):
self.tens = arg[0]
self.ones = arg[1]
else:
self.number = arg
def getNumber(self):
return self.tens*10 + self.ones
def setNumber(self, value):
if value < 0 or value > 99:
raise ArgumentException("Must in [0, 99]")
self.tens = value // 10
self.ones = value % 10
number = property(getNumber, setNumber, None, "Complete number, [0-99]")
x = SillyDecimal()
x.number, x.tens, x.ones # returns (17, 7, 1)
Notice that while "tens", "ones" and "number" all appear as
attributes, only "number" has its input validated. Since the class is
designed to only hold numbers 0 - 99, one can 'break' it by setting
self.tens=11, for example. Of course this is just a toy example, but
the point should be clear: when is it pythonic to do
attribute/property validation?
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor