list property fires get on append

Diez B. Roggisch deets at nospam.web.de
Sun Jan 6 06:51:49 EST 2008


Soviut schrieb:
> On Jan 6, 3:03 am, Fredrik Lundh <fred... at pythonware.com> wrote:
>> i... at neustyle.com wrote:
>>> I've created a class that has a property which points at a private
>>> list.  When I try to use the append() function on this list property,
>>> the fget method is fired rather than the fset method.  If I directly
>>> set my property to a literal list, the set method fires.
>>> # this fires a get for some reason
>>> hierarchy.children.append( Hierarchy.Hierarchy())
>> that's the expected behaviour: you're *fetching* the "children"
>> attribute in order to modify it, you're not replacing it.
>>
>> reading up on Python's object model might be helpful.
>>
>> </F>
> 
> I figured that an append would be treated as a set since I'm adding to
> the list.  But what you say makes sense, although I can't say I'm
> happy with the behaviour.  Is there any way I can get the append to
> fire a set?  I'm thinking of properties from my C# background where i
> believe that manipulation such this would be considered a set.

No, it wouldn't. It's simply this:

c = a.b

Now what does that trigger? Obviously a get on a for the attribute b. 
But what you do with c afterwards is totally up to you. You can alter 
it, or you can leave it. Think of this example:

c = a.b
if random() > .5:
   c.append(1)
else:
   print c[0]

How should the interpreter or C# runtime know when a.b is executed how c 
will be treated?

What you _can_ do is to not return the actual list-object in get, but 
instead a proxy that will notify the owner of the list of all methods 
called.


Diez



More information about the Python-list mailing list