Advanced Variable - variable references, variable and immutable types. Local and global variables

Advanced variable (understand)

aims

  • Variable references
  • And immutable type variable
  • Local and global variables

01. Variable references

  • Variables and data are stored in the memory of
  • In Pythonthe parameter of the transfer function and the return value are by reference passed

1.1 The concept of reference

In Pythonthe

  • Variables and data are stored separately
  • Data stored in a memory location
  • Variables stored in the address data in memory
  • Variables in the recorded data addresses , called references
  • Use id()function you can view the data stored in the variable where the memory address

Note: If the variable is defined, when assigned to a variable, essentially modified the data references

  • Variable no longer on the previous data references
  • Variable instead of a reference to the assignment of new data

1.2 变量引用Example

In Pythonthe name, it is similar to the variable paper notes attached to the data on

  • The definition of an integer variable a, and assigned1
Code Icon
a = 1 Here Insert Picture Description
  • The variable is aassigned2
Code Icon
a = 2 Here Insert Picture Description
  • Definition of an integer variable b, and the variable avalue is assigned tob
Code Icon
b = a Here Insert Picture Description

Variable bis the second digital affixed 2on the label

Pass parameters and return values ​​of function 1.3

In Pythonthe function of argument / return value are is by reference to the passed

def test(num):

    print("-" * 50)
    print("%d 在函数内的内存地址是 %x" % (num, id(num)))

    result = 100

    print("返回值 %d 在内存中的地址是 %x" % (result, id(result)))
    print("-" * 50)

    return  result

a = 10
print("调用函数前 内存地址是 %x" % id(a))

r = test(a)

print("调用函数后 实参内存地址是 %x" % id(a))
print("调用函数后 返回值内存地址是 %x" % id(r))

02. The variable type and immutable

  • Immutable type , the data memory can not be modified:

    • Digital type int, bool, float, complex,long(2.x)
    • String str
    • Tuple tuple
  • Variable type , the data memory can be modified:

    • List list
    • dictionary dict
a = 1
a = "hello"
a = [1, 2, 3]
a = [3, 2, 1]
demo_list = [1, 2, 3]

print("定义列表后的内存地址 %d" % id(demo_list))

demo_list.append(999)
demo_list.pop(0)
demo_list.remove(2)
demo_list[0] = 10

print("修改数据后的内存地址 %d" % id(demo_list))

demo_dict = {"name": "小明"}

print("定义字典后的内存地址 %d" % id(demo_dict))

demo_dict["age"] = 18
demo_dict.pop("name")
demo_dict["name"] = "老王"

print("修改数据后的内存地址 %d" % id(demo_dict))

Note: The dictionary key can only use immutable types of data

note

  1. The variable type of data changes, by a method to achieve
  2. If you give a variable type of variable, the assignment of a new data, reference will be modified
    • Variable no longer on the previous data references
    • Variable instead of a reference to the assignment of new data

Hash (hash)

  • PythonThere is a built-in name is hash(o)a function of
    • Receiving a hard type of data as a parameter
    • Return result is an integer
  • 哈希It is an algorithm , and its role is to extract the data signature (fingerprint)
    • The same content to get the same result
    • Different content to get different results
  • In Python, set the dictionary key-value pairs , it will first to keybe hashdecided how to save the data dictionary in memory, in order to facilitate the subsequent operation of the dictionary: add, delete, change, search
    • Value pairs keymust be immutable data type
    • Key-value pairs valuemay be any type of data

03. Local and global variables

  • Local variables are the internal function of the variables defined only in the internal function
  • Global variables are defined outside the function variable (not a function defined in a), all functions inside can use this variable

Tip: In other development languages, most do not recommend the use of global variables - variable scope is too large, resulting in poor maintenance program!

3.1 Local variables

  • Local variables are the internal function of the variables defined only in the internal function
  • After the function is executed, the local variables inside a function, the system will be recovered
  • Different functions can be defined a local variable with the same name, but with each other does not affect

The role of local variables

  • Inside the function using, temporary hold internal functions require data
def demo1():

    num = 10

    print(num)

    num = 20

    print("修改后 %d" % num)


def demo2():

    num = 100

    print(num)

demo1()
demo2()

print("over")

Local variable life cycle

  • The so-called life cycle is variable from being created to the recovery system process
  • Local variables in a function execution will be created
  • After the function is executed local variable are systematically recycled
  • Local variables lifecycle within, it can be used to store internal data using the temporary function

3.2 Global Variables

  • Global variables in a function outside the definition of variables, all internal functions can use this variable
# 定义一个全局变量
num = 10


def demo1():

    print(num)


def demo2():

    print(num)

demo1()
demo2()

print("over")

Note that when the function execution: to deal with variables will be:

  1. First look inside the function if there is to specify the name of a local variable , if any, directly
  2. If not, look for an external function if there is to specify the name of the global variable , if any, directly
  3. If not, the program error!

1) function can not be directly modified 全局变量的引用

  • Global variables are defined outside the function variable (not a function defined in a), all functions inside can use this variable

Tip: In other development languages, most do not recommend the use of global variables - variable scope is too large, resulting in poor maintenance program!

  • Inside the function can obtain the corresponding reference data by a global variable
  • However, it is not allowed to directly modify the global variable references - the value of using a global variable modified assignment
num = 10


def demo1():

    print("demo1" + "-" * 50)

    # 只是定义了一个局部变量,不会修改到全局变量,只是变量名相同而已
    num = 100
    print(num)


def demo2():

    print("demo2" + "-" * 50)
    print(num)

demo1()
demo2()

print("over")

Note: Just inside the function defines a local variable only, just the same variable name - can not directly modify global variables inside a function value

2) modify global variables inside a function value

  • If you need to modify the global variable in a function, you need globalto be declared
num = 10


def demo1():

    print("demo1" + "-" * 50)

    # global 关键字,告诉 Python 解释器 num 是一个全局变量
    global num
    # 只是定义了一个局部变量,不会修改到全局变量,只是变量名相同而已
    num = 100
    print(num)


def demo2():

    print("demo2" + "-" * 50)
    print(num)

demo1()
demo2()

print("over")

3) global variable defined positions

  • To ensure that all functions are able to correctly use global variables, should global variables defined above other functions
a = 10


def demo():
    print("%d" % a)
    print("%d" % b)
    print("%d" % c)

b = 20
demo()
c = 30

note

  • Because the global variable c, after calling the function is only defined when the function is executed, the variable has not been defined, so the program will complain!

Code structure diagram is as follows

Here Insert Picture Description

4) recommended that a global variable named

  • In order to avoid local and global variables confusion, when you define global variables, some companies have developed a number of requirements, such as:
  • Global variables should be increased before the name g_or gl_prefix

Tip: The specific format requirements, companies may be required some differences

Published 299 original articles · won praise 48 · views 30000 +

Guess you like

Origin blog.csdn.net/xie_qi_chao/article/details/104877065