The variable length parameters, function objects, nested namespaces and Scope

Come, come, it really came, Super Typhoon Lekima has come, in the evening is eating a delicious dinner, eating into the wind and rain outside, the people are messy, do not Tucao, or learn it !

The variable length parameters, function objects, nested namespaces and Scope

A variable length parameter

The variable length parameter of 1.1 *

* Receiving overflow position with arguments, stored as tuples, * then copied to the parameter, the parameter name * args fixed

def sum_self(*args):   # 用*接收位置实参1,2,3,4,存储为元组(1,2,3,4),赋值给args
    res=0
    for num in args:
        res+=num
    return res
res = sum_self(1,2,3,4)
print(res)     # 10

The variable length argument of 1.2 *

The arguments * * the parameter values ​​will be removed after the cycle, broken into position argument

def func(x,y,z,*args):
    print(x,y,z,args)

func(1,*(1,2),3,4)   #  *循环取出(1,2),打散成位置实参,这样位置实参就变成1,1,2,3,4,\
#  形参x,y,z对应的实参就为1,1,2,形参中用*args接收溢出的位置实参3,4,存储为元组(3,4)

The variable length parameter of 1.3 **

Parameter of the spill-over-all key argument, and then store the dictionary form, then the dictionary assigned to the parameters of. Note that: the parameter name after the convention is kwargs **

def func(**kwargs):
    print(kwargs)
func(a=5,b=6)      # 形参中的**接收溢出的两个关键字实参,存储为字典{'a':5,'b':6},并赋值给kwargs

The variable length argument of 1.4 **

The argument **, ** value of the cycle parameters will be removed after **, broken into Keyword argument. After an argument in touch with whenever **, it is the key argument, it should be immediately broken into keyword arguments to see

ef func(x,y,z,**kwargs):
    print(x,y,z,kwargs)     #  1 3 4 {'a': 1, 'b': 2}
func(1,3,4,**{'a':1,'b':2})

Second, the function object

  • Define a function: the function is the first-class objects, i.e. the data processing function may be used as
# 把函数当做对象来用
def func():
    print('from func')

print(func)   # 这里函数func就可以当做数据来print,直接print(函数名),会输出函数的内存地址,<function func at 0x000001EBDC641E18>
  • Function name identical to a variable name, a variable name conventional method i.e., have the same function name, can be used to reference, as an argument to a function, as the return value of the function, as the container class data element type
  • To function func defined above, for example, we have the following four functions:

2.1, references

a = 1
print(a)  # 变量名

b = a  # b =1
# 变量名可以被引用,函数名也可以被引用

f = func  # func可以加()调用,那么f也可以加()调用
print(f)    # 打印func内存地址,<function func at 0x000001EBDC641E18>
f()  # 相当于func() ,打印结果为from func

2.2, as the arguments passed to a formal parameter parameter parameter

def f2(name):  # name = func
    name()  # func()   

f2(func)     # 这整个函数就能实现函数func()的调用,输出结果为from func

2.3, can be used as an element type in the data containers

lt = [1, 2, a, func]
lt[-1]()   # 直接实现func调用功能,最后输出结果from func

2.4 can be used as the return value of the function

def f3(name):  # name = func
    return name  # name = func

res = f3(func)  # res = func
print(res)    # 打印func的内存地址,<function func at 0x000001EBDC641E18>
res()     # 调用函数func(),打印结果为from func

Third, the nested functions

3.1 nested definitions function

  • Internal function defined functions can not be used inside a function defined in an external function
def f1():
    def f2():
        print('from f2')
    f2()

f2()  # NameError: name 'f2' is not defined,在函数外部就不能使用内部函数f2
  • Correct nested definitions

    def f1():
        def f2():
            print('from f2')
        f2()
    f1()
  • Function parameter passing through the area or circumference of circular

from math import pi

def circle(radius, action='area'):   # radius为半径
    def area():
        return pi * (radius**2)

    def perimeter():       # 定义周长函数
        return 2*pi*radius
    if action == 'area':
        return area()
    else:
        return perimeter()


print(f"circle(10): {circle(10)}")
print(f"circle(10,action='perimeter'): {circle(10,action='perimeter')}")

3.2 nested function calls

def self_max(x,y):
    if x>y:
        return x
    return y
def self_4_max(x,y,z,a):
    res1=self_max(x,y)     # 在这个函数内调用上面的函数
    res2=self_max(z,a)
    res=self_max(res1,res2)
    return res
res=self_4_max(10,40,20,80)
print(res)             # 80

Fourth, namespace and scope

4.1 namespace

Namespace used to store variable names and function names

4.1.1 built-in namespace

  • Python interpreter is unique, storage python interpreter that comes with the name, such asint、float、len

  • Function calls have to define, has never been defined. Python interpreter starts up automatically when the python to open up space for a built-in name of these built-in python, python interpreter after stopping explanation will destroy

  • When the interpreter starts to take effect, fail when the interpreter is closed

    len([1, 2, 3])
    int('10')

4.1.2 The global name space

  • Global namespace: In addition to the built-in and a local name, the rest are stored in the global namespace, such as the following codex、func、l、z
  • Global needs its own definition, it may have a global name space after the python file is executed, after the end of the file will be destroyed
x = 1   #  全局名称空间

def func():
    pass

l = [1, 2]    # 内置名称空间
if 3 > 2:
    if 4 > 3:
        z = 3

4.1.3 local name space

  • The local name space: in the function definition of variables and function names are stored in the local name space
  • Local also needs its own definition, have to take effect after the function call, the call will be destroyed after the end of
def f1():
    def f2():    # f2为局部名称空间
        print('from f2')
    f2()

f1()

4.1.4 three kinds namespace execution order

Because .py file is opened by the Python interpreter, so it must be built after the name space in Python interpreter has finished loading, began to open the file, this time will produce a global name space, but there is a certain function in the file when called, it will begin to produce local namespace == therefore load order for the namespace: built-in - "global -" local ==.

4.1.5 three kinds namespace search order

As the name space is used to store a binding relationship between the variable name and value, so whenever you want to find the name, it must be found in one of the three, look for the following order:
start looking from the current location, if the current location location for the local namespace == the search order is: local - "global -" built ==.

x = 1
y = 2
len = 100  # 为内置名称空间

def func():
    y = 3
    len = 1000    
    print(f"y: {y}")     # 先在局部内找到y,所以y=3,输出为3
    print(f"len: {len}")   # 先局部内找到len,就不需要再到全局和内置找,因此输出为1000
    # print(a)  # NameError: name 'a' is not defined ,从当前位置到局部再到全局再到内置都没有找到a,所以报错

func()

46名称空间与作用域-简单.png?x-oss-process=style/watermark

4.2 Scope

4.2.1 global scope

Global Scope: Global effective, global survival, and includes built-in global name space variables, variables in global scope can only be used in the big picture

# 全局作用域
x = 1

def bar():
    print(x)

bar()

4.2.2 local scope

The local scope: local name space variables can only be used locally, the local effective, temporary storage, only contains the local name space,

# 局部作用域
x = 1
def f1():
   
    print(x)  # f1中的局部
f1()
def f2():
    x = 2  # x=2只能在f2中使用
    f1()

f2()  # f1中的局部和f2中的局部互不干涉 
# 最终输出结果为1

4.2.3 Notes

== scope definition phase relations in the function have been identified dead, regardless of the calling function ==

# 作用域注意点
x = 1

def f1():  # 定义阶段x=1
    print(x)

def f2():
    x = 2
    f1()

f2()

The output is 1

lt = [1,2,3]  # 作用域关系仅适用不可变数据类型,不适用于可变数据类型

def f1():
   lt.append(4)

f1()

print(lt)    # [1,2,3,4]

4.2.4 application scope and function objects

# 作用域应用
def f1():
    def inner():
        print('from inner')
    return inner

f = f1()  # 把局部定义的函数放在全局之中

def bar():
    f()   # 起到调用函数f1的作用

bar()
-------------------------------------------------------------------------------
输出结果为from inner

4.3 Supplementary knowledge

4.3.1 global keyword

Modify variables global scope

x = 1

def f1():
    x = 2

    def f2():
        #  global x  # 修改全局
        x = 3
    f2()

f1()
print(x)
---------------------------------------------------------------------------------

输出为1
x = 1

def f1():
    x = 2

    def f2():
        global x  # 修改全局
        x = 3
    f2()

f1()
print(x)
---------------------------------------------------------------------------------
输出为3

4.3.2 nonlocal keyword

Modify variables local scope

x = 1

def f1():
    x = 2

    def f2():
        #         nonlocal x
        x = 3

    f2()
    print(x)

f1()

2

x = 1

def f1():
    x = 2

    def f2():
        nonlocal x
        x = 3

    f2()
    print(x)

f1()

3

4.3.3 Notes

  1. In the local want to modify the global variable type, it does not require any statement can be modified directly.

  2. In the local immutable type if you want to modify global, the need to use global statement, declared as global variables can be modified directly.

    lis = []
    
    
    def f1():
        lis.append(1)
    
    
    print(f"调用函数前: {lis}")
    f1()
    print(f"调用函数后: {lis}")

    Before calling function: []
    after calling function: [1]

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11329829.html