pythonic use of properties?

Gerald Klix Gerald.Klix at klix.ch
Fri Apr 15 02:23:17 EDT 2005


The python rationale is "We are all consenting adults.".

You shoukd change "tens" to "_tens" and "ones" to "_ones", in order to
syntacticly mark these attributes as internal.
If someone not consenting, wants to mess with your internal
representation, it's his fault.

HTH,
Gerald



Marcus Goldfish schrieb:
> I'd like advice/opinions on when it is appropriate to do
> attribute/property validation in python.  I'm coming from a C#/Java
> background, where of course tons of "wasted" code is devoted to
> property validation.  Here is a toy example illustrating my question:
> 
> #   Example: mixing instance attributes with properties.  Is it pythonic to
> #   validate property data in setters?  Since tens and ones are never
> #   validated, the class can be "broken" by setting these directly
> class SillyDecimal(object):
>    """A silly class to represent an integer from 0 - 99."""
>    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)
> 
> Even though "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.  Should tens and ones be made into full-fledged properties
> and validated?  Should number have no validation?  Is it more pythonic
> to encapsulate tightly, or rely on "responsible use."
> 
> Marcus

-- 
GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634




More information about the Python-list mailing list