Python variables and constants

Source: Internet
Author: User
Tags constant definition garbage collection

1. What is a variable

A=1, where a is the variable name and 1 is its value. In the process of running the program, the value of the variable will generally change, in memory will be dedicated to open a space, to hold the value of the variable, and the variable will point to the value of the memory space. As opposed to a variable is a constant, the value of the constant will not change during program operation.

2. Naming conventions for variables
    • Variable names can only be any combination of letters, numbers, or underscores
    • The first character of a variable name cannot be a number
    • The following keywords cannot be declared as variable names
      [‘and‘, ‘as‘, ‘assert‘, ‘break‘, ‘class‘, ‘continue‘, ‘def‘, ‘del‘, ‘elif‘, ‘else‘, ‘except‘, ‘exec‘, ‘finally‘, ‘for‘, ‘from‘, ‘global‘, ‘if‘, ‘import‘, ‘in‘, ‘is‘, ‘lambda‘, ‘not‘, ‘or‘, ‘pass‘, ‘print‘, ‘raise‘, ‘return‘, ‘try‘, ‘while‘, ‘with‘, ‘yield‘]

There are generally 2 ways to name variables:
1) Use an underscore to separate words and words in a variable

hello_kitty=‘abc‘

2) Capitalize the first letter of each word in the variable

helloKitty=‘abc‘

Tip: The first way to recommend it ~

3. Definition and assignment of variables

A=1 is the assignment process of a variable, the value of the left side of the equal sign "=" is assigned to the variable A on the right, and the process already contains the declaration and definition of the variable, each variable needs to be assigned and reused, and the variable is created after it is assigned. Unlike other languages, such as in C, where variables must be defined before they are assigned, Python does not need to assign values directly to the type of the variable, and thePython interpreter determines the type of the object based on the syntax and operands .

Dynamic type language and static type language
    • Static type language : The data type is determined during compilation and, when encoded, must explicitly specify the data type of the variable before assigning a value.
      Major languages: C, C + +, Java, object-c ...
      For example, the assignment statement for Java is as follows:
      String str = "abc";  char sex = ‘M‘;  

      ?

    • Dynamic Type language : The data type is not determined during compilation, and the type binding of the variable is deferred to the run stage. A type declaration is not required before a variable is used.
      Major languages: Python, Perl, Ruby, Erlang, PHP ...
      For example, a python assignment statement:
      >>> str = ‘abc‘>>> var = 1

In Python, you can repeatedly assign values to the same variable and each assignment has an inconsistent data type (the type () function looks at the data type):

>>> abc = 1>>> type(abc)<class ‘int‘>               # abc 为 int 类型>>> abc = 1.2>>> type(abc)<class ‘float‘>            # abc为 float 类型>>> abc = ‘hello‘>>> type(abc)<class ‘str‘>              # abc为 字符串 类型

Memory Plots:

The process of assigning variables

An assignment operation in the program, for example: abc=1, can be roughly divided into two steps in memory:
1) A space in memory to store the value 1
2) Create a variable ABC in memory and point to the value 1

After the assignment is complete, if you modify the value of ABC, the Python interpreter does not modify the value stored in the memory space that the variable ABC points to, but instead re-opens up a memory space, stores the new value, and the variable ABC again points to the newly opened memory space:

>>> abc = 1>>> id(abc)1465150944>>> abc=‘hello kitty‘>>> id(abc)1730859168688

Note: the function ID () is used to view the memory address of the variable ~

Python Small integer Object pool

Example 1:

>>> a = 10>>> b = 10>>> id(a)1465151232>>> id(b)1465151232

Example 2:

>>> a = 300>>> b = 300>>> id(a)1730858159920>>> id(b)1730858412880

As mentioned above, changing the value of a variable in Python is not directly modified in the corresponding memory space, but requires malloc to reallocate memory and then recycle it after it is exhausted. To improve efficiency, the Python interpreter stores small integers [-5,257] in a small integer object pool, which is the small_ints array. Small_ints caches all integers between [-5,257], and the small_ints array persists after the Python interpreter is initialized. If the value of a variable is within the range of [-5,257), it is obtained directly from the small_ints array without the need to allocate memory space.

The range of small integers is [-5,257), to modify the source code implementation that needs to be modified by Python

So as shown in Example 1: Different variables whose values are the same small integer, these variables refer to the same object. If the value of an integer is not within the range of [-5,257], the Python interpreter will store it in the Pyintblock, which is not introduced here ~

Other ways to assign values

Multiple assignments
Assign values to multiple variables at the same time.

a = b = c = 1            # a,b,c的值都为1

Multi-value Assignment
Multiple variables, multiple values, one after the other.

a, b, c = 1, 2, 3        # a = 1,b = 2,c = 3

Decomposition Assignment
Assigning values to multiple variables after a tuple is decomposed

a, b, c = (1,2,3)      # a = 1,b = 2,c = 3
4, Python reference count and garbage collection mechanism reference count

Python uses reference counts to track objects in memory. When an object is created and assigned to a variable, the object's reference count is set to 1.
When the object is referenced again, the reference count is added to 1. The reference count also decreases (for example, the DEL variable name or the value of the variable), when the reference count is 0, meaning that the object has not been used ~

Del statement
The DEL statement deletes a reference to the object, del Syntax: Del obj[, obj2[, ... Objn]]
del xtwo actions after execution:
1) Delete x from the current namespace
2) The reference count of the object pointed to by X minus 1

Garbage collection mechanism

The Python GC module tracks and reclaims garbage by reference counting. On the basis of the reference count, you can also solve the problem of circular references that can be generated by the container object through mark-clear (Mark and sweep). Further increase the efficiency of garbage collection by "generational recycling" (generation collection) for space Exchange time.

5. Constants

A constant is a quantity that does not change while the program is running, and the C language has a special constant definition syntax: const int a = 60; Constants can not be changed after the definition, if the changes will be error, Python does not have a modifier like const, that is, there is no specific syntax for defining constants, the general conventional variable name in the form of an all-uppercase representation of this is a constant ~

NAME=kitty

.................^_^

Python variables and constants

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.