8.9 day12

Vararg

Vararg: refers to the function call, the number of parameters passed may not be fixed

The function is called, the value of no more than two pass mode, one is the position of the argument, and the other argument is a keyword, and therefore must have formal parameters there are two solutions, in order to receive the overflow location argument (*) with the keyword arguments (**)

A variable length parameter of *

Parameter of the spill-over-all position of the argument, and then stored tuple, the tuple is then assigned to the parameters of. Note that: * the name of the parameter convention for the args.

def sum_self(*args):
    res = 0
    for num in args:
        res += num
    return res


res = sum_self(1, 2, 3, 4)
print(res)
10

Second, the variable-length argument *

The argument , will be the value of the parameter after the extraction cycle, broken into position argument. After arguments encountered whenever the tape , it is the position argument should be broken into a position immediately see argument.

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


func(1, *(1, 2), 3, 4)
1 1 2 (3, 4)

Third, the variable length parameter * *

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

def func(**kwargw):
    print(kwargw)


func(a=5)
{'a': 5}

Fourth, the variable-length argument * *

The argument , will be the value of the parameter after the extraction cycle, broken into Keyword argument. After the encounter whenever arguments in the band , it is the key argument, it should be immediately broken into keyword arguments to see.

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


func(1, 3, 4, **{'a': 1, 'b': 2})
1 3 4 {'a': 1, 'b': 2}

Fifth, the variable-length parameters are applied

def index(name, age, sex):
    print(f"name: {name}, age: {age}, sex: {sex}")


def wrapper(*args, **kwargs):
    print(f"args: {args}")
    print(f"kwargs: {kwargs}")
    index(*args, **kwargs)


wrapper(name='nick', sex='male', age=19)
args: ()
kwargs: {'name': 'nick', 'sex': 'male', 'age': 19}
name: nick, age: 19, sex: male

Six key parameter named

There is now a demand: the user function argument must pass by keyword.

def register(x, y, **kwargs):
    if 'name' not in kwargs or 'age' not in kwargs:
        print('用户名和年龄必须使用关键字的形式传值')
        return
    print(kwargs['name'])
    print(kwargs['age'])


register(1, 2, name='nick', age=19)
nick
19

Name Keyword parameter: function definition stage, parameters are named after the * key parameter.

Features: In the pass value must be passed in accordance with the value of key = value manner and key must be named keyword arguments specified parameter name.

def register(x, y, *, name, gender='male', age):
    print(x)
    print(age)


register(1, 2, x='nick', age=19)  # TypeError: register() got multiple values for argument 'x'

Nested functions

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
def f1():
    def f2():
        print('from f2')
    f2()


f1()
from f2

Now there is a demand, by giving a pass parameters to the function of a determined area of ​​a circle or circumference of a circle. That is thrown into the pile of tools within the toolbox, and then want to get a tool, available directly from the toolbox on the line.

from math import pi


def circle(radius, action='area'):
    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')}")
circle(10): 314.1592653589793
circle(10,action='perimeter'): 62.83185307179586

Second, the nested function calls

def max2(x, y):
    if x > y:
        return x
    else:
        return y


def max4(a, b, c, d):
    res1 = max2(a, b)
    res2 = max2(res1, c)
    res3 = max2(res2, d)
    return res3


print(max4(1, 2, 3, 4))
4

Function inside the function only inside the function call, you can not call outside the function, you will know why this happens through the next study.

def f1():
    def f2():
        print('from f2')
    f2()

f2()  # NameError: name 'f2' is not defined

Namespaces

Namespace (name spaces): In the memory management when that chapter, we said that to create a variable is actually opened up a new space in memory. But we've been avoiding storing variable names, in fact, there is room for a binding relationship between a variable name and variable memory storage in memory, and this space is called a namespace.

1.1 built-in namespace

Built-in namespace: Store Pyhton interpreter that comes with the name, such asint、float、len

Life cycle: when the interpreter started to take effect, fail when the interpreter is closed

1.2 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

Life cycle: when the file is executed into effect, expire after file execution

x = 1


def func():
    pass


l = [1, 2]

if 3 > 2:
    if 4 > 3:
        z = 3

1.3 The local name space

The local name space: the name of the function body for storing generated during a function call, such as the following codef2

Life Cycle: take effect during the function call when the file is executed, expire after the function execution

def f1():
    def f2():
        print('from f2')
    f2()

f1() 

1.4 load 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 name space, the name space for the loading order: built-in - "global -" local.

10

Scope

Domain refers to a region, i.e. the region scope of action.

2.1 global scope

Global Scope: Global effective, global survival, and includes built-in namespace global name space.

# 全局作用域
x = 1


def bar():
    print(x)


bar()
1

2.2 local scope

The local scope: local small, temporary storage, containing only the local name space.

# 局部作用域
def f1():
    def f2():
        def f3():
            print(x)
        x = 2
        f3()
    f2()


f1()
2

Guess you like

Origin www.cnblogs.com/bjlxxbj/p/11329086.html