When described as follows, a and b seem to point to exactly the same object (2 in this case).
a = 2
b = 2
Exactly the same. * "The same object" * in English. I had a lot of questions, so I looked it up. First, let's itemize the questions.
If you think about it carefully, this was what I looked up in the previous article.
To summarize briefly
If the exact same object already exists,
Refer to that same object to save memory.
If the same object does not exist, it will be newly created.
In other words, if a = 3
is newly entered, a new object will be created. And is it that `` `b = 2``` is saved as it is?
Of course, since it is a beginner's memo writing, more complicated things may be happening in the fundamental part, but since this definition can explain without contradiction, I will proceed as it is for the time being.
To see if it's true, look at what's called the memory space address using the id function, which you can see directly.
As you can see by examining id (), it seems that the identification value is used as the return value. In other words, if they point to the same object, the return value is the same, and if they are different, the return value is also different.
Now, let's find out if it really belongs to *** together ***.
test.py
a = 2
b = 2
id(a) #4401166416
id(b) #4401166416
id(a) == id(b) #True It's a hassle to see the numbers==I tried using it.
Apparently it's likely. In other words, the rules when a new object is created will be as follows.
Still suspicious, Kan Chin defined a new `` `c = 3``` and tried another experiment.
test.py
c = 3
id(c) #4401166448
id(a) == id(c) #False
#After this, rewrite a to 3 and check if it is the same as c.
a = 3
id(a) #4401166448
id(a) == id(c) #True
And became together wonderfully. In other words
If the same object exists
No new object is created.
It looks like. (* Some corrections have been made in the postscript)
I don't know what it's useful for, but the content is strange and interesting.
Such a design method is called the Flyweight pattern (it is "flyweight" because it consumes less memory). For your reference.
... apparently ... Thank you very much.
Apparently, if the value is large, a new object will be created even if the value is exactly the same.
Here is what I tried to do.
test
d = 50000
e = 50000
id(d) #4406088592
id(e) #4404350832
id(d) == id(e) #False
It's surprisingly interesting to see how the contents of the system are stored.
Recommended Posts