On Apr 28, 10:59 pm, "Gabriel Genellina" > def property_default(prop_name, default_value=None, doc=None): > > attr_name = '_'+prop_name > > def fget(self, attr_name=attr_name, > default_value=default_value): > return getattr(self, attr_name, default_value) > > def fset(self, value, > attr_name=attr_name, > default_value=default_value): > if value == default_value: > delattr(self, attr_name) > else: > setattr(self, attr_name, value) > > return property(fget=fget, fset=fset, doc=doc) > > When setting the same value as the default, the instance attribute is > removed (so the default will be used when retrieving the value later). I > think this is what you intended to do.
Note that this will fail if the value is already equal to the default and you try to reset it to the default, so it needs an extra hasattr(self, attr_name) before the delattr. Regardless, I would be surprised with the following behaviour: >>> r = Rectangle() >>> r.length = 4 >>> type(r.length) <type 'int'> >>> r.length = 12 >>> type(r.length) <type 'float'> Another simpler alternative would be to (ab)use a decorator: def defaultproperty(func): attr = '_' + func.__name__ default = func.func_defaults[0] return property( fget = lambda self: getattr(self, attr, default), fset = lambda self,value: setattr(self, attr, value), doc = func.__doc__) class Rectangle(object): '''A beautiful Rectangle''' @defaultproperty def length(default=12.0): '''This is the length property''' George -- http://mail.python.org/mailman/listinfo/python-list