dw-python-函数与Lambda表达式

带dw-python的均为datawhale-python教程
学习的打卡,内容较乱,懒得整理

函数的调用

def printme(str):
    print(str)


printme("我要调用用户自定义函数!")  # 我要调用用户自定义函数!
printme("再次调用同一函数")  # 再次调用同一函数
temp = printme('hello') # hello
print(temp)  # None

default argument

形参和实参的绑定关系,只在函数调用时才会生效、绑定,调用结束后,立刻解除绑定。
default argument(默认参数)的形参在函数第一次命名时候就指定了,实参可传值,但是应该是类型不能变;然而如果用可变类型作为默认参数,可以迭代。
Python 唯一支持的参数传递 是共享传参,Call by Object (Call by Object Reference or call by Sharing)

以下内容详见b站视频解说
4.7.1. Default Argument Values
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

This function can be called in several ways:

giving only the mandatory argument: ask_ok(‘Do you really want to quit?’)

giving one of the optional arguments: ask_ok(‘OK to overwrite the file?’, 2)

or even giving all arguments: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.

The default values are evaluated at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):
    print(arg)

i = 6
f()

will print 5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

This will print

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

5. 命名关键字参数

def functionname(arg1, arg2=v, *args, *, nkw, **kw):
    "函数_文档字符串"
    function_suite
    return [expression]
  • *, nkw - 命名关键字参数,用户想要输入的关键字参数,定义方式是在nkw 前面加个分隔符 *。
  • 如果要限制关键字参数的名字,就可以用「命名关键字参数」
  • 使用命名关键字参数时,要特别注意不能缺少参数名。

【例子】

def printinfo(arg1, *, nkw, **kwargs):
    print(arg1)
    print(nkw)
    print(kwargs)


printinfo(70, nkw=10, a=1, b=2)
# 70
# 10
# {'a': 1, 'b': 2}

printinfo(70, 10, a=1, b=2)
# TypeError: printinfo() takes 1 positional argument but 2 were given
  • 没有写参数名nwk,因此 10 被当成「位置参数」,而原函数只有 1 个位置函数,现在调用了 2 个,因此程序会报错。

nonlocal

def make_counter():
    count = 0

    def check_counter():
        print(count)

    check_counter()

    def modify_counter():
        nonlocal count
        count += 1
        print(count)

    modify_counter()


make_counter()

闭包

def outer():
    x = 1

    def inner():  # 在outer函数内部再定一个函数
        # x = 2  
        print('from inner', x)

    return inner  # outer函数返回inner函数对象


f = outer()  # 现在的f是一个全局变量,同时是inner函数对象
print(f)
x = 3  # 这个x = 3并不能改变inner函数外层的x
f()

def foo():
    x = 4  # 这个x = 4 同样也不能改变
    f()  # 全局作用域在任意位置都可以调用

foo()

你可能感兴趣的:(Python)