python - Why does assigning to True/False not work as I expect? -


as part of answering question, wrote following code behaviour seems bizarre @ first glance:

print true                    # outputs true true = false;    print true   # outputs false true = true;     print true   # outputs false true = not true; print true   # outputs true 

can explain strange behaviour? think has python's object model i'm not sure.

it's version 2.5.2 under cygwin.

python has these 2 (among others) builtin objects. objects; in beginning, don't have names yet, know refer to, let's call them 0x600d , 0xbad.

before starting execute python (2.x) script, name true gets bound object 0x600d, , name false gets bound object 0xbad, when program refers true, looks @ 0x600d.

because 0x600d , 0xbad know used names true , false, that's output when printed, i.e. __str__ method of 0x600d returns 'true' , on.

true = false 

now binds name true different object. on, both names true , false refer same object 0xbad, which, when printed, outputs false.

true = true 

doesn't anything: takes object referred name true, , binds new (and old) name true object. since (because of previous step) true refers 0xbad before this, still refers 0xbad after this. hence, printing still outputs false.

true = not true 

first takes object name true bound to, 0xbad. gives object not operator. not doesn't care (or know) name used here refer 0xbad, knows when given 0xbad should return 0x600d. return value given assignment operator =, binding name true object.

since name true once more refers object 0x600d, calling print true outputs true, , world again.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -