Advanced Python's function (day09)

  Today, we contacted the main part of the advanced function, generally speaking contents trap function, namespaces and closures scope, functions and nested functions and function of these knowledge points

1. The function of the trap:

  The main function of the trap here say is the default function of trap questions:

def func(l = []):
    l.append(1)
   print(l)
func()

  Let's look at this code, in the function parameter, we have a default value of l is the type of the array, while the argument of function, we do not pass any value. When we then call the function, the value of its output are:

1

  This is no doubt, but we are more than a few times to print it?

def func(l = []):
    l.append(1)
    print(l)
func()        [1]
func()        [1, 1]
func()        [1, 1, 1]  

  Which many people would think that it would be printed shape:

[1]
[1]
[1]

  This is what we call a trap, but, so what causes this problem?

  Actually very simple, when we called, we were not to pass parameters, then each execution is the default value, this default value has become a common , ( default parameters each call, all calls that can be shared the default parameter
if the value of the default parameter is a variable data type, then the function is called every time when if you do not pass a value to the public this type of data resources.)

  for example:

 

func () [1 ] 
func () [ 1, 1 ] 
function ([]) [ 1 ] 
func () [ 1, 1, 1]

 

  We can see that when we pass the arguments of the past, it will pass the value used to calculate, if not he will use the shared before the default parameter list this happens, then the dictionary it? (Said earlier, when the default parameters are variable parameter data type parameter will make the situation occurs shared), let a specific dictionary look

def func(key ,l = {}):
    l[key] = 'a'
    print(l)
func('name')    #{'name': 'a'}
func('sex')     #{'name': 'a', 'sex': 'a'}

  The same principle, or the emergence of sharing formal parameters. So pay attention, when our daily programming, to take advantage of this law defaults trap, to deal with the problems we encountered, that is, when the data type of the variable time parameter (lists, dictionaries, collections), we You should begin to pay attention.

 

2. The function and scope of the namespace:

Here we recall the first time python code to run functions that encounter is how to do.

After the python interpreter started, it opens up a space in memory

Whenever there is a variable, put the correspondence between the variable name and the value recorded.

But when faced with the function definition interpreter only symbolic function name is read into memory , it was aware of the existence of this function, as a function of internal variables and logic interpreter does not care.

Such as the implementation of the time function call, python interpreter will then open up a memory to store this function in the content , this time, was concerned about the function inside which variables, and the function of the variables stored in the newly opened up memory. The variables can only function within the function of use, and will function as finished, all the contents of this memory will be cleared.

We give this "relationship store the names and values," the space has a name - called the namespace

Space "of the relationship between the variable name and value" Run the code in the beginning, to create a storage called a global name space , temporary space opened up in the run function is called in the local namespace

# Namespace three
# built-in namespace - python interpreter
    # is the python interpreter to store a name you can start to use the built-in namespace
    # built-in name is loaded into memory at boot time interpreter in
# global name space - we write the code but not the function code
    # is in the process of the program is executed from top to bottom in order to load into memory
    # placed all variables and function names we set
# local namespace - function
    # is the name of a function defined inside
    # when calling this function will generate namespace with the end of the function performed by this namespace disappear again

# locally: you can use a global, built-in namespace names
# in global: can use the built-in namespace names, but you can not use topical in
# built-in: You can not use the names of local and global

# Under normal circumstances, the direct use of the built-in name
# When we defined and built-in namespace of the same name in the global name, will use a global name
# myself sometimes when I do not find my superiors asked for a
# If he did not find it to be on a higher level if the parent did not find the built-in namespace are not on the error
# multiple functions should have a more independent local namespace, do not share with each other

 

#func -> memory address of the function
# function name () function is called
the memory address of the function # () function is called

 

The scope of two kinds #
# global scope - the whole picture - and built the global namespace names are part of the global scope --globals ()
# local scope - in the role of local - function (local name space the name belongs to the local scope) --locals ()

 

# For immutable data types, but watch variables in the global scope of the local
# but can not directly modify
# If you want to modify, you need to add global statement at the beginning of the program
if declared in a local (function) a global variable # , then the global variable will be valid in all operating variables local
# a. 1 =
# 2 = B
# DEF FUNC ():
# = X 'AAA'
# = Y 'BBB'
# Print (about locals ())
# Print (Globals ())
#
# FUNC ()
# Print (Globals ())
# Print (locals ()) # local

#globals always print the name of the global
#locals output locals what the position where the

# 1 = a
# DEF FUNC (A):
# 2 = A
# A return
#
# A = FUNC (A)
# Print (A)

 

3. function nested definitions

Function nested definitions #
variable # internal function may use external functions
# A. 1 =
# Outer DEF ():
# A. 1 =
# Inner DEF ():
# 2 = A
# Inner2 DEF ():
# A # nonlocal Statement an upper layer of the first local variable
# a + = 1 # immutable data types of modifications
# Inner2 ()
# Print ( '## ## a:', a)
# Inner ()
# Print ( '** a ** : ', a)

# Outer ()
# Print (' global: ', a)

#nonlocal only be used for local variables from the current function to find the nearest one of the top local variables in
variable # nonlocal declared inside a function of changes will be Effect of the current function from the nearest local variable layer
# global invalid
# local only affects one of the most recent
# 0 = a
# Outer DEF ():
# a # =. 1
# Inner DEF ():
# # 2 = A
# Inner2 DEF ():
# Nonlocal A
# Print (A)
# Inner2 ()
# Inner ()
#
# # Outer ()

# DEF FUNC ():
# Print (123)
#
# # FUNC () # function name is the memory address
# func2 = func # function name can be assigned
# func2 ()
#
# L = [FUNC, func2] # function name can be used as a container type of element
# Print (L)
# for I in L:
# I ()

DEF FUNC ():
    Print (123)

Wahaha DEF (F):
    F ()
    return function name F # can be used as the return value of a function

qqxing = wahaha (func) # name can be given as a parameter
qqxing ()

4. closure

 

def outer():
    a = 1
    def inner():
        print(a)
    return inner
inn = outer()
inn()

# import urllib  #模块
from urllib.request import urlopen
# ret = urlopen('http://www.xiaohua100.cn/index.html').read()
# print(ret)
# def get_url():
#     url = 'http://www.xiaohua100.cn/index.html'
#     ret = urlopen(url).read()
#     print(ret)
#
# get_url()

def get_url():
    url = 'http://www.xiaohua100.cn/index.html'
    def get():
        ret = urlopen(url).read()
        print(ret)
    return get

get_func = get_url()
get_func()

 

 

  

Guess you like

Origin www.cnblogs.com/if-it-is-possible/p/11470433.html