函数进阶

案例

python基础语法案例

Python 基础语法案例

下面这段代码可以直接复制到 .py 文件中运行,覆盖函数进阶、异常、文件操作和类型注解。

from dataclasses import dataclass
from pathlib import Path
from tempfile import TemporaryDirectory
 
 
def total(*numbers):
    return sum(numbers)
 
 
def build_profile(name, **extra):
    return {"name": name, **extra}
 
 
def make_multiplier(factor):
    def multiply(value):
        return value * factor
 
    return multiply
 
 
def divide(a, b):
    if b == 0:
        raise ValueError("b must not be zero")
    return a / b
 
 
@dataclass
class Student:
    name: str
    score: int
 
 
def passed(students: list[Student], line: int = 60) -> list[str]:
    return [student.name for student in students if student.score >= line]
 
 
def file_case():
    with TemporaryDirectory() as temp_dir:
        path = Path(temp_dir) / "demo.txt"
        path.write_text("hello\npython\n", encoding="utf-8")
        with path.open("a", encoding="utf-8") as file:
            file.write("file demo\n")
        print(path.read_text(encoding="utf-8"))
 
 
def main():
    print("var args:", total(1, 2, 3))
    print("kwargs:", build_profile("Tom", age=20, city="Beijing"))
 
    double = make_multiplier(2)
    print("closure:", double(10))
 
    for value in [2, 0]:
        try:
            print("divide:", divide(10, value))
        except ValueError as error:
            print("handled:", error)
 
    students = [Student("Tom", 80), Student("Lucy", 95), Student("Jack", 50)]
    print("passed:", passed(students))
 
    file_case()
 
 
if __name__ == "__main__":
    main()
指向原始笔记的链接

函数返回多个返回值

def test_return()
	return 1, 2, "Hello", True
 
# 接受值一一对应
x, y, z, result = test_return()

函数多种传参方式

# 位置参数
def test(name, age, number)
	print(name, age, number)
 
# 关键字参数
# 1. 可不按顺序匹配
# 2. 可与位置参数混用(必须在前面一一对应,)
def test(name, age, number)
	print(name, age, number)
 
test(age = 20, name = 'Tom', number = '1234')
 
# 位置参数混用例子
def test(name, age, number)
	print(name, age, number)
 
test('Tom', number = '1234', age = 20)
 
# 以上output:Tom 20 1234
 
# 缺省参数(有默认值,必须写在后面)
def test(name, age, number='4567')
	print(name, age, number)
 
test('Tom', 10)
test('Tom', 10, 1234)
#output:
# Tom 10 4567
# Tom 1o 1234
 
# 不定长参数(位置不定长)
def test(*args)
	print(type(args),args)
 
test('Tom', 20, '1234')
# output:<class tuple> ('Tom', 20, '1234')
 
# 不定长参数(关键字不定长)
def test(**kwargs)
	print(type(kwargs),kwargs)
 
test(age = 20, name = 'Tom', number = '1234')
# output:<class dict> {'name':Tom, 'age':20, 'number':1234}

函数做参数

是一种计算逻辑传递,而非数据传递

def test(add):
	result = add(1, 2)
	print(result)
 
def compute(x, y):
	return x + y
 
test(compute)
# output:3

lambda匿名函数

lambda 传入参数:函数体(一行代码) 没有函数名 只使用一次 只能写一行

def test(add):
	result = add(1, 2)
	print(result)
 
test(lambda x, y: x + y)