Inexplicable behavior in simple example of a set in a class

Chris Angelico rosuav at gmail.com
Sat Jul 2 20:46:02 EDT 2011


On Sun, Jul 3, 2011 at 8:23 AM, Saqib Ali <saqib.ali.75 at gmail.com> wrote:
> So just out of curiosity, why does it work as I had expected when the
> member contains an integer, but not when the member contains a set?

It's not integer vs set; it's the difference between rebinding and
calling a method. It's nothing to do with object orientation; the same
happens with ordinary variables:

>>> a=b=1
>>> a,b
(1, 1)
>>> a=2
>>> a,b
(2, 1)

>>> c=d=[]
>>> c,d
({}, [])
>>> c.append("Test")
>>> c,d
(['Test'], ['Test'])

But:
>>> c=['Foobar']
>>> c,d
(['Foobar'], ['Test'])

When you do a=2 or c=['Foobar'], you're rebinding the name to a new
object. But c.append() changes that object, so it changes it
regardless of which name you look for it by.

Chris Angelico



More information about the Python-list mailing list