On 9/30/2010 8:43 PM, Steven D'Aprano wrote:
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
value

*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.

*test.prop.append('World')

*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?

test.prop.sort()

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.

You can't.

What problem are you trying to solve? There is likely another way to
solve it. (Not necessarily an easy way, but we'll see.)



So I'll have to create my own object which modifies each method to fire off the set method if the old form and the new form are unequal, there is no easy way?
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to