[Tutor] Mutable Properties
Steven D'Aprano
steve at pearwood.info
Wed Sep 8 23:22:53 CEST 2010
On Thu, 9 Sep 2010 06:59:57 am Chris King wrote:
> Dear Tutors,
> I noticed that when you use a property to represent a mutable
> value, I you try to use its methods, it will directly change the
> value returned. I know this happens because I'm not really assigning
> it to something new, but changing whats already there, which won't
> fire off the set method. I was wondering if there was a way around
> this.
You're going to need to give an example of:
(1) what you do;
(2) what you want to happen; and
(3) what actually happens.
The simplest example I can think of is:
class K(object):
def __init__(self):
self._private = []
def _getter(self):
return self._private
def _setter(self, value):
self._private = list(value)
seq = property(_getter, _setter)
And in use:
>>> k = K()
>>> k.seq
[]
>>> k.seq.append(1)
>>> k.seq
[1]
Works fine.
--
Steven D'Aprano
More information about the Tutor
mailing list