This is the third day of my participation in Gwen Challenge
1. Basic concepts
1.1 object
In Python, everything is an object. Each object consists of an ID, a type, and a value.
Let’s define a variable Name with a value of “JUEJING”
The id of Name is 2729105983472, which is the address of object “JUEJING”
1.2 reference
In Python, variables become references to: objects. Because a variable stores the address of an object.
Variables refer to “objects” by address
Variables are located in: stack memory
Objects are located in: heap memory
Key points:
Python is dynamically typed language variables do not need to be explicitly typed; the Python interpreter automatically gets the data type based on the object the variable refers to
Python is a strongly typed language. Every object needs a data type, and only the operations that that type supports are supported
Here’s an example:
1.3 Stack memory and heap memory
2. Memory distribution of strings
2.1 Declare the memory distribution of characters
To assign a string to a variable, the heap in memory is checked to see if the string already exists
-
The variable points directly to the memory address of the string if it exists
-
If not, create a new string directly in heap memory and pass the memory address to the variable
Myname = "JUEJING" Myname = "JUEJING" Print (Name,MyName) print(id(Name),id(MyName))Copy the code
2.2 Memory distribution of immutable Data Types
Python standard syntax does not allow strings to modify internal data directly
Print (Name) print(id(Name)) print(Name)Copy the code
Twice the results before and after printing -- -- -- -- -- -- -- -- -- -- -- JUEJING 4545145648 -- -- -- -- -- -- -- -- -- -- -- -- -- to modify the Name print -- -- -- -- -- -- -- -- -- -- -- -- -- for example, 4545145712Copy the code
2.3 Concatenated String memory distribution
-
String assignments are declared directly in quotes, and memory is allocated in the static area to create the data
-
The string is assigned by concatenation, which completes the memory allocation of the result of the operation in heap memory
H3 = "helloJUEJING" # 4545145904 h4 = h1+h2 print(id(h3)) # 4545146160 print(id(h4)) # 4545146032Copy the code
conclusion
The core of python string memory allocation is the stack memory and heap memory understanding, which will be covered in more detail later
All right, so that’s how python string memory works
I’m learning Python. See you next time