I was surprised at how to save objects with python, which is lean and very energy-saving.

Surprised story

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.

  1. If you point to the same place and change a, does b also change?
  2. Is that true?

Question 1: Isn't it rewritten?

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.

Question 2: Check if it is true (use of id function)

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.

Postscript

From yuba

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.

shiracamus made a correction in the comment.

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

I was surprised at how to save objects with python, which is lean and very energy-saving.
How to use is and == in Python
Three things I was addicted to when using Python and MySQL with Docker
[Python] How to save images on the Web at once with Beautiful Soup
Python> set> Convert with set ()> dictionary is only key> I was taught how to convert the values of dictionary to set / dir ({}) / help ({}) / help ({} .values)
I tried to read and save automatically with VOICEROID2 2
I want to handle optimization with python and cplex
I tried to automatically read and save with VOICEROID2
I was surprised at how Python's ternary operator works
I was addicted to scraping with Selenium (+ Python) in 2020
I was surprised to receive a nice review when I wrote Python to CheckIO and its explanation
[Python] What is a tuple? Explains how to use without tuples and how to use it with examples.
I tried to simulate how the infection spreads with Python
[Python] How to play with class variables with decorator and metaclass
How to do Bulk Update with PyMySQL and notes [Python]
How to scrape at speed per second with Python Selenium
I tried to make GUI tic-tac-toe with Python and Tkinter
How to log in to AtCoder with Python and submit automatically
Operate Jupyter with REST API to extract and save Python code
I want to solve APG4b with Python (only 4.01 and 4.04 in Chapter 4)
How to import CSV and TSV files into SQLite with Python
What I was addicted to with json.dumps in Python base64 encoding
How to make a surveillance camera (Security Camera) with Opencv and Python
I tried to make a periodical process with Selenium and Python
I tried to find out if ReDoS is possible with Python
How to deal with errors when installing Python and pip with choco
I was addicted to confusing class variables and instance variables in Python
How to utilize Python with Jw_cad (Part 1 What is external transformation)
How to use Python with Jw_cad (Part 2 Command explanation and operation)
How to build Python and Jupyter execution environment with VS Code
Python: How to use async with
How to get started with Python
I played with PyQt5 and Python3
How to calculate date with python
I want to debug with Python
[Python] How to save the installed package and install it in a new environment at once Mac environment
The 16th offline real-time how to write problem was solved with Python
With PEP8 and PEP257, Python coding that is not embarrassing to show to people!
[Introduction to Python] How to judge authenticity with if statement (True and None)
How to write offline real time I tried to solve E11 with python
I was addicted to creating a Python venv environment with VS Code
Use Python from Java with Jython. I was also addicted to it.
The file name was bad in Python and I was addicted to import
Read CSV file with Python and convert it to DataFrame as it is
The 15th offline real-time how to write problem was solved with python
How to query BigQuery with Kubeflow Pipelines and save the result and notes
How to write offline real time I tried to solve E12 with python
The tree.plot_tree of scikit-learn was very easy and convenient, so I tried to summarize how to use it easily.
I want to detect objects with OpenCV
How to package and distribute Python scripts
How to split and save a DataFrame
Convert memo at once with Python 2to3
How to install and use pandas_datareader [Python]
Fractal to make and play with Python
I wanted to solve ABC160 with Python
How to work with BigQuery in Python
I want to analyze logs with Python
How to do portmanteau test with python
I want to play with aws with python
python: How to use locals () and globals ()
How to enter Japanese with Python curses