[Tutor] Mutable Properties

Alan Gauld alan.gauld at btinternet.com
Fri Oct 1 09:46:11 CEST 2010

"Chris King" <g.nius.ck at gmail.com> wrote

>     I noticed that when you make a property to represent a mutable 
> value
> *class Obj(object):
>     prop = property(get, set)

> test.prop = ['Hello']

Let's be clear, here you are assigning a list object to your property.

> and then try and use one of its methods.
> *test.prop.append('World')

And here you use a method of that list object.
The property is just a name that refers to the list object.
You are not using a method of the property you are using
a method of the object to which the property refers.

> *It will treat it as a get, not a set.

Because it is a get. Your line of code is a shorthand way
of writing

theList = test.prop

> *Even thou you are basically changing its value.

You are not changing the property's value, it is still the
same list object. The property has done exactly what
you asked it to do - get you the list object so that you
can perform an append operation on it.

> *I know this happens because I'm not technically setting it to 
> something
> else, just getting one of its properties.

You are getting the object you assigned because that's
what you asked it to do. Python is not psychic, it cannot
guess what you will do with the property value.

> I was wondering how to make it fire off set to for certain methods.

The property mechanism only works for access to the property value.
It has no way of knowing what you will do with that value once you get 
What you need to do is create your own kind of list that prints 
when you access the list. It is the list you are manipulating not the
test class.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list