>>> x = 100
>>> y = 100
>>> x == y
True
>>> x is y
True
>>> x = 1000
>>> y = 1000
>>> x == y
True
>>> x is y
False
The is operator compares whether the left and right are references to the same object. See the following example.
>>> x = []
>>> y = []
>>> x is y
False
>>> z = x
>>> x is z
True
>>> x.append(42)
>>> y
[]
>>> z
[42]
x and y are separate list objects created separately. So x is y will be False, and changing x will not affect y.
On the other hand, z refers to the same object as x. So x is z will be True, and if you change x (the list object referenced by), then z will of course change as well.
An object whose value that the object indicates is determined when the object is created and does not change thereafter is called an immutable. The integer is immutable. See the sample code below.
>>> x = 42
>>> y = x
>>> x is y
True
>>> x += 1
>>> x
43
>>> y
42
>>> x is y
False
Immediately after y = x
, x is y
was True because x and y point to the same object representing 42.
x + = 1
assigns another object representing 43 to x. So x is y
becomes False.
The Flyweight pattern is used for optimization when immutable objects such as integer types are used in large numbers. Instead of creating an object with that value every time a new value is needed, by sharing an existing object
There are merits such as.
(As of 09/07/2016) In CPython, integers from -5 to 256 are managed by the flyweight pattern, and the same object is always used. Therefore, if the value is in this range, x is y
may be True even for objects that should have been created separately.
Recommended Posts