[Tutor] Mutable Properties
steve at pearwood.info
Fri Oct 1 02:43:48 CEST 2010
On Fri, 1 Oct 2010 10:24:50 am Chris King wrote:
> Dear Tutors,
> I noticed that when you make a property to represent a mutable
> *class Obj(object):
> def get(self):
> print 'Get'
> return self.prop
> def set(self, new):
> print 'Set'
> self.prop = new
> prop = property(get, set)
> test = Obj()
> test.prop = ['Hello']
> and then try and use one of its methods.
> *It will treat it as a get, not a set.
That's because it is a get. You get the property, and then you call one
of its methods. How could it be any different?
The object stored in the property could be anything. How can the class
know which methods modify it in place, and which ones don't?
Did this modify the list or not?
> *Output: Get
> *Even thou you are basically changing its value.
But changing a mutable value means modifying it in place, not
re-assigning it. This is no different from:
mylist = test.prop # this is a get
mylist.append("something") # change it in place
Since there is no assignment to prop, there is no set.
> *Before: ['Hello']
> After: ['Hello', 'World']
> *I know this happens because I'm not technically setting it to
> something else, just getting one of its properties.
> I was wondering how to make it fire off set to for certain methods.
What problem are you trying to solve? There is likely another way to
solve it. (Not necessarily an easy way, but we'll see.)
More information about the Tutor