Python- function basis (2)

Vararg

Katachisan

*形参

Receiving extra argument position, stored in the form of a tuple

**形参

Keyword argument receiving excess, in order to save a dictionary

Arguments

*实参

The broken tuple type, passed parameter *

**实参

The break up a dictionary, passed parameter **

Function object

  • It can be used as reference

    x = 'hello nick'
    y = x
    
    f = func
    print(f)
  • As the container element

    l = [x]
    
    function_list = [func]
    function_list[0]()
  • As a function parameter

    len(x)
    
    def foo(m):
        m()
    
    foo(func)
  • The return value as a function of a function

    def foo(x):
        return x
    
    res = foo(func)
    print(res)
    res()

Nested functions

Print multiplication table

for i in range(1,10):
    for j in range(1,i+1):
        print(f"{i}*{j}={i*j}",end="")
    print()

Namespace and scope

Namespaces

Built-in namespace

Placed built-in method

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

The local name space

Function defined variables and functions

Life Cycle: During the function call into effect, ending execution failure

Global name space

In addition to the built-in local and global name space are placed

Life cycle: when the file is executed take effect after the end of the file fails

Execution order

Built-in - "Global -" local

Search Order

Built-in from the current position of the local - - "global"

Scope

Global scope

Global effective, global survival

Local scope

Temporary storage, only contains the local name space

global

Modify variables in global scope.

x = 1


def f1():
    x = 2

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


f1()
print(x)

nonlocal

x = 1


def f1():
    x = 2

    def f2():
        nonlocal x
        x = 3

    f2()
    print(x)


f1()

important point:

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

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}")

Guess you like

Origin www.cnblogs.com/qinyujie/p/11564410.html