python advanced variable basis _

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 Python function of parameter passing and return values are by reference passed

1.1 The concept of reference

In Python

  • 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
  • Using the id () function can save the data to see where the variable memory address

    Note: If the variable is defined, when assigned to a variable, essentially modified the data reference
    variable is no longer a reference to the previous data
    variable instead of a reference to the assignment of new data

Variable reference example 1.2

In Python, similar to the name of the variable paper notes attached to the data on

  • Definition of an integer variable a, and the value of 1
Code Icon
a = 1 python advanced variable basis _
  • Will be assigned to a variable 2
Code Icon
a = 2 python advanced variable basis _
  • B define an integer variable, and the value of a variable is assigned to b
Code Icon
b = a python advanced variable basis _

The variable b is attached to the second digital label 2

Pass parameters and return values ​​of function 1.3

In Python, the function 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:
    the digital type int, bool, float, complex, long (2.x)
    string str
    tuple tuple
  • Variable type , data in 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": "name1"}

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

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

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

note:

  • The key can only be used dictionaries immutable types of data
  • The variable type of data changes, by a method to achieve
  • If you give a variable type of variable, the assignment of a new data, reference can modify
    variables no longer on previous data reference
    variable instead of a reference to the assignment of new data

Hash (hash)

  • Python is built into a function called names hash (o) of
    receiving a hard type of data as a parameter
    to return the result is an integer
  • It is a hashing algorithm , and its role is to extract the data pattern (fingerprint)
    the same content to obtain the same result
    different contents obtained different results
  • In Python, set the dictionary key-value pairs , it will first hash the key to decide how to save the data dictionary in memory, in order to facilitate the subsequent operation of the dictionary: add, delete, change,
    keys on the key must be immutable data
    value pairs value may 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, 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")

Function is executed, you will need to be addressed variables: Note:

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

1) function can not directly modify the global variable references

  • 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 of the same variable name it - 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 to use global 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

python advanced variable basis _

4) recommended that a global variable named

  • In order to avoid local and global variables confusion, when you define global variables, some companies there will be some development requirements, such as:
    global variables before the name should be increased g_ or gl_ prefix
    Tip: The specific format requirements, each company requires some differences may

Guess you like

Origin blog.51cto.com/tobeys/2440269