Basis Functions

Function basis

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 number of elongated *

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 func(*args):
    res = 0
    for num in args:
        res += num
    return res

res = func(1, 2, 3, 4)
print(res)

Two variable-length argument of *

The arguments *, * \ * value will be taken out cycling parameters, broken into position argument. After arguments whenever encountered with *, 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, 2, 3, 5, 4)

1 2 3 (5, 4)

Three variable parameters of the elongated **

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

def func(**kwargs):
    print(kwargs)

func(a=4)

{'a': 4}

IV. The variable length argument **

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

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

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

1 2 3 {'a': 1, 'b': 2}

V. variable-length parameters are applied

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

def func2(*args, **kwargs):
    print(f"arge: {args}")
    print(f"kwargs: {kwargs}")
    func(*args, **kwargs)

func2(name='kang', age=19, sex='male')

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

VI. Named keyword arguments

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'

Function object

Functions are first-class objects, i.e. function may be used as the data processing.

def func():
    print('from func')


print(func)
<function func at 0x10af72f28>

First, the four functions function object

x = 'hello nick'
y = x

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

2. as a parameter passed to a function

len(x)


def foo(m):
    m()


foo(func)
from func

3. The return value can be used as a function of

def foo(x):
    return x


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

4. The types of elements can be used as a container

l = [x]

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

Nested functions

I. nested function definition

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 #

In a demand, a function to pass through the area A reference to a circumference of a circle or 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

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

First, the 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

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

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

46 namespace and scope - simple .png x-oss-process = style / watermark?

1.4 load order
1.5 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 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()
y: 3
len: 1000
x = 1


def func():
    print(x)


x = 10
func()
# 10

Second, the scope

46 namespace and scope -? Map .jpg x-oss-process = style / watermark

2.1 global scope

# 全局作用域
x = 1


def bar():
    print(x)


bar()
#1

2.2 local scope

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


f1()
#2

2.3 Notes

# 作用域注意点
x = 1


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


def f2():
    x = 2
    f1()


f2()
#1

2.4 Application of scopes function object +

from inner

Third, additional knowledge points

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

3.2 nonlocal keyword

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

3.3 Notes **

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/kangwy/p/11329367.html