property, how to use it?

Larry Bates lbates at syscononline.com
Fri May 13 14:13:09 EDT 2005


class Age:
    def __init__(self, years=None):
        if years is None: self.years=0
        else: self.years=years

    def __setattr__(self, key, value):
        if key == "years":
            if value < 0:
                print "ERROR-Years cannot be less than zero, setting to zero"
                self.years=0
                return

        self.__dict__[key]=value
        return

if __name__=="__main__":
    a=Age()
    #
    # Following will print zero because it is the default
    #
    print a.years
    #
    # Try to set negative
    #
    a.years=-1
    #
    # Other attributes work just fine
    #
    a.yyy=10

Larry Bates


Steve wrote:
> Hi,
> 
> Read this:
> http://www.python.org/2.2.3/descrintro.html#property
> 
> If you still don't understand or are confused about it's usage, ask here.
> 
> Hint: Suppose you need to create an Age class with a 'years' attribute
> and ensure that, (assuming I create an object a = Age())
> 1) when one tries to access 'a.years', a '0' would be returned even if
> the value was not set or was set to a negative value, and
> 
> 2) If a value is assigned to the 'years' attribute, we should check
> for negative values.
> 
> HTH
> Regards
> Steve




More information about the Python-list mailing list