object-identity

When does Python create new list objects for empty lists?

岁酱吖の 提交于 2019-11-29 03:38:35
The following makes sense to me: >>> [] is [] False Given that lists are mutable, I would expect [] to be a new empty list object every time it appears in an expression. Using this explanation however, the following surprises me: id([]) == id([]) True Why? What is the explanation? In the first example, [] is not [] precisely because the lists are mutable. If they weren't, they could safely map to the same one without issue. In the second example, id([]) creates a list, gets the id, and deallocates the list. The second time around it creates a list again , but "puts it in the same place"

In Ruby, why does inspect() print out some kind of object id which is different from what object_id() gives?

谁说我不能喝 提交于 2019-11-27 18:09:28
When the p function is used to print out an object, it may give an ID, and it is different from what object_id() gives. What is the reason for the different numbers? Update: 0x4684abc is different from 36971870 , which is 0x234255E >> a = Point.new => #<Point:0x4684abc> >> a.object_id => 36971870 >> a.__id__ => 36971870 >> "%X" % a.object_id => "234255E" Arkku The default implementation of inspect calls the default implementation of to_s , which just shows the hexadecimal value of the object directly, as seen in the Object#to_s docs (click on the method description to reveal the source).

&#39;is&#39; operator behaves differently when comparing strings with spaces

耗尽温柔 提交于 2019-11-26 15:27:35
I've started learning Python (python 3.3) and I was trying out the is operator. I tried this: >>> b = 'is it the space?' >>> a = 'is it the space?' >>> a is b False >>> c = 'isitthespace' >>> d = 'isitthespace' >>> c is d True >>> e = 'isitthespace?' >>> f = 'isitthespace?' >>> e is f False It seems like the space and the question mark make the is behave differently. What's going on? EDIT: I know I should be using == , I just wanted to know why is behaves like this. Elazar Warning: this answer is about the implementation details of a specific python interpreter. comparing strings with is ==bad

&#39;is&#39; operator behaves differently when comparing strings with spaces

霸气de小男生 提交于 2019-11-26 04:26:28
问题 I\'ve started learning Python (python 3.3) and I was trying out the is operator. I tried this: >>> b = \'is it the space?\' >>> a = \'is it the space?\' >>> a is b False >>> c = \'isitthespace\' >>> d = \'isitthespace\' >>> c is d True >>> e = \'isitthespace?\' >>> f = \'isitthespace?\' >>> e is f False It seems like the space and the question mark make the is behave differently. What\'s going on? EDIT: I know I should be using == , I just wanted to know why is behaves like this. 回答1: Warning