python-day12 (formal learning)

Vararg

The 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

Variable-length argument of *

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)

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}

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}

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

Named keyword parameter

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'

Function object

Four functions

Quote

x = 'hello nick'
y = x

f = func
print(f)
<function func at 0x10af72f28>

As an argument to a function

len(x)


def foo(m):
    m()


foo(func)
from func

It can be used as the return value of the function

def foo(x):
    return x


res = foo(func)
print(res)
res()
<function func at 0x10af72f28>
from func

It can be used as container type elements

l = [x]

function_list = [func]
function_list[0]()
from func

Nested functions

Nested function definition

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

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

Namespace and scope

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.

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

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

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() 

Loading 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.

Find the 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 name space, look for the following order: local - "global -" built.

x = 1
y = 2
len = 100


def func():
    y = 3
    len = 1000
    print(f"y: {y}")
    print(f"len: {len}")
    # print(a)  # NameError: name 'a' is not defined


func()

and 3

Only 1000

x = 1


def func():
    print(x)


x = 10
func()

10

Scope

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

Global scope

# 全局作用域
x = 1


def bar():
    print(x)


bar()

1

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

important point

Note that: the scope of the relationship between the function definition stage fixed die, regardless of the function was called.

# 作用域注意点
x = 1


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


def f2():
    x = 2
    f1()


f2()

1

The scope of application function object +

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


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


def bar():
    f()


bar()

from inner

supplement

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

nonlocal keyword

Modify the local variable domain

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

Guess you like

Origin www.cnblogs.com/leaf-wind/p/11329120.html