百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python 函数进阶的10大技巧,不允许你还不会

off999 2025-07-08 22:07 4 浏览 0 评论

函数是Python编程的核心构建块,掌握高级函数技巧可以显著提升代码质量和开发效率。以下是Python函数编程的进阶技巧:

1. 函数参数高级用法

1.1 灵活的参数处理

# 位置参数、默认参数、可变参数
def flexible_func(a, b=2, *args, **kwargs):
    print(f"a={a}, b={b}, args={args}, kwargs={kwargs}")

flexible_func(1)                          # a=1, b=2, args=(), kwargs={}
flexible_func(1, 3, 4, 5, x=6, y=7)      # a=1, b=3, args=(4, 5), kwargs={'x':6, 'y':7}

1.2 仅关键字参数(Python 3+)

def kw_only_arg(*, name, age):
    print(f"{name} is {age} years old")

kw_only_arg(name="Alice", age=25)  # 正确
# kw_only_arg("Alice", 25)        # 错误,必须使用关键字参数

1.3 参数类型提示(Python 3.5+)

from typing import Optional, List, Union

def type_hinted_func(
    name: str,
    age: int = 18,
    hobbies: Optional[List[str]] = None
) -> Union[str, None]:
    """函数带有类型注解"""
    if hobbies is None:
        hobbies = []
    if age >= 18:
        return f"{name} likes {', '.join(hobbies)}"
    return None

2. 函数式编程技巧

2.1 Lambda函数

# 简单lambda
square = lambda x: x ** 2

# 在sorted中使用
users = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
sorted_users = sorted(users, key=lambda u: u['age'])

2.2 map/filter/reduce

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# map应用函数
squares = list(map(lambda x: x**2, numbers))

# filter筛选元素
evens = list(filter(lambda x: x % 2 == 0, numbers))

# reduce归约计算
sum_total = reduce(lambda x, y: x + y, numbers)

2.3 偏函数(Partial)

from functools import partial

def power(base, exponent):
    return base ** exponent

# 创建固定exponent为2的新函数
square = partial(power, exponent=2)
print(square(5))  # 25

3. 装饰器高级用法

3.1 带参数的装饰器

def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def greet(name):
    print(f"Hello {name}")

greet("Alice")  # 打印3次

3.2 类装饰器

class CountCalls:
    def __init__(self, func):
        self.func = func
        self.num_calls = 0
    
    def __call__(self, *args, **kwargs):
        self.num_calls += 1
        print(f"Call {self.num_calls} of {self.func.__name__}")
        return self.func(*args, **kwargs)

@CountCalls
def say_hello():
    print("Hello!")

say_hello()  # 记录调用次数

3.3 多个装饰器叠加

def decorator1(func):
    def wrapper():
        print("Decorator 1 before")
        func()
        print("Decorator 1 after")
    return wrapper

def decorator2(func):
    def wrapper():
        print("Decorator 2 before")
        func()
        print("Decorator 2 after")
    return wrapper

@decorator1
@decorator2
def my_func():
    print("Original function")

# 执行顺序:decorator1 -> decorator2 -> my_func

4. 生成器与协程

4.1 生成器函数

def countdown(n):
    print("Starting countdown")
    while n > 0:
        yield n
        n -= 1
    print("Blast off!")

for num in countdown(5):
    print(num)

4.2 协程与yield

def coroutine_example():
    print("Coroutine started")
    while True:
        x = yield
        print(f"Received: {x}")

coro = coroutine_example()
next(coro)  # 启动协程
coro.send(10)  # 发送值
coro.send(20)

4.3 yield from (Python 3.3+)

def generator1():
    yield from range(5)
    yield from 'abc'

list(generator1())  # [0,1,2,3,4,'a','b','c']

5. 闭包与作用域

5.1 闭包函数

def make_multiplier(factor):
    def multiplier(x):
        return x * factor
    return multiplier

times2 = make_multiplier(2)
times5 = make_multiplier(5)
print(times2(4))  # 8
print(times5(4))  # 20

5.2 nonlocal关键字

def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

c = counter()
print(c(), c(), c())  # 1, 2, 3

6. 动态函数操作

6.1 动态创建函数

def create_function(name):
    def new_function():
        print(f"I am {name}")
    return new_function

func1 = create_function("Alice")
func2 = create_function("Bob")
func1()  # I am Alice
func2()  # I am Bob

6.2 函数属性

7. 函数缓存与优化

7.1 使用lru_cache

from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

7.2 单分派泛函数

from functools import singledispatch

@singledispatch
def process(data):
    print("Processing generic data")

@process.register(str)
def _(text):
    print(f"Processing text: {text}")

@process.register(int)
def _(number):
    print(f"Processing number: {number*2}")

process("hello")  # Processing text: hello
process(10)      # Processing number: 20

8. 上下文管理器

8.1 使用生成器实现

from contextlib import contextmanager

@contextmanager
def managed_file(filename, mode):
    try:
        f = open(filename, mode)
        yield f
    finally:
        f.close()

with managed_file('test.txt', 'w') as f:
    f.write('Hello')

8.2 多个上下文管理器

with open('input.txt') as f_in, open('output.txt', 'w') as f_out:
    for line in f_in:
        f_out.write(line.upper())

9. 函数签名与内省

9.1 获取函数签名

from inspect import signature

def func(a, b=2, *args, **kwargs):
    pass

sig = signature(func)
print(str(sig))  # (a, b=2, *args, **kwargs)

9.2 参数绑定

bound_args = sig.bind(1, 2, 3, x=4)
print(bound_args.arguments)  # {'a':1, 'b':2, 'args':(3,), 'kwargs':{'x':4}}

10. 异步函数(Python 3.5+)

10.1 基本异步函数

import asyncio

async def fetch_data():
    print("Start fetching")
    await asyncio.sleep(2)
    print("Done fetching")
    return {'data': 1}

async def main():
    result = await fetch_data()
    print(result)

asyncio.run(main())

10.2 多个协程并行

async def main():
    task1 = asyncio.create_task(fetch_data())
    task2 = asyncio.create_task(fetch_data())
    
    await task1
    await task2

这些函数进阶技巧可以帮助您编写更灵活、更强大的Python代码。掌握这些概念后,您将能够更好地利用Python的函数式编程特性,构建更模块化、更高效的应用程序。

相关推荐

python pip 命令 参数(python pip命令用不了)

usage:python[option]...[-ccmd|-mmod|file|-][arg]...Options(andcorrespondingenvironm...

Python 包管理:uv 来了!比 pip 快 100 倍的神器,开发者的终极选择?

为什么Python开发者需要uv?Python生态虽繁荣,但包管理一直是痛点:pip安装慢如蜗牛、依赖冲突让人头秃、虚拟环境配置繁琐……直到uv横空出世!这个用Rust语言打造的...

UV:Python包管理的未来已来!比pip快100倍的新选择

引言Python开发者们,是否厌倦了pip的缓慢安装速度?是否希望有一个更快、更现代、更高效的包管理工具?今天,我要向大家介绍一个革命性的Python包管理工具——UV!UV由Rust编写,是pip和...

「Python」 常用的pip命令和Django命令

pip命令如何根据关键词找到PyPI(Python包仓库)上的可用包#方法1:直接访问PyPI官网,输入关键词搜索#方法2#为何不用pipsearchdjango?因为这个命令已不可...

python包管理工具pip freeze详解(python工具包怎么用)

freeze就像其名字表示的意思一样,主要用来以requirement的格式输出已安装的包,这里我们主要讨论以下3个选项:--local、--user、--pathlocal--local选项一般用在...

python包管理工具pip config详解(python的pulp包)

pipconfig主要包含以下子命令:set、get、edit、list、debug、unset。下面我们逐一介绍下它们。pipconfigset这个命令允许我们以name=value的形式配...

pip常用命令,学Python不会这个寸步难行哦(26)

小朋友们好,大朋友们好!我是猫妹,一名爱上Python编程的小学生。欢迎和猫妹一起,趣味学Python。今日主题学习下pip的使用。pip什么是pippip全称PythonPackageIndex...

Python pip 包管理需知(python的包管理)

简介在Python编程中,pip是一个强大且广泛使用的包管理工具。它使我们能够方便地安装、升级和管理Python包。无论是使用第三方库还是分享自己的代码,pip都是我们的得力助手。本文将深入解析pip...

比pip快100倍的Python包安装工具(python如何用pip安装包)

简介uv是一款开源的Python包安装工具,GitHubstar高达56k,以性能极快著称,具有以下特性(官方英文原文):Asingletooltoreplacepip,pip-tool...

Python安装包总报错?这篇解决指南让你告别pip烦恼!

在Python开发中,pip是安装和管理第三方包的必备工具,但你是否经常遇到各种报错,比如无法创建进程、权限不足、版本冲突,甚至SSL证书错误?这些问题不仅浪费时间,还让人抓狂!别担心!本文整理了...

pip vs pipx: Python 包管理器,你选择哪个?

高效的包管理对于Python开发至关重要。pip和pipx是两个最常用的工具。虽然两者都支持安装Python包,但它们的设计和用例却大相径庭。本文将探讨这些差异,解释何时使用每种工具,并...

【python】5分钟掌握pip(包管理)操作

安装一个软件包从庞大的仓库中找到一个库,将其导入您的环境:pipinstallnumpy2.已安装软件包列表调查您领域内存在的库的概要,注意它们的版本:piplist3.升级软件包赋予已安装...

Python pip安装与使用步骤(python的pip安装方法)

安装和使用Python的包管理工具pip是管理Python包和依赖项的基础技能。以下是详细的步骤:安装pip使用系统包管理器安装Windows:通常,安装Python时会自动安装p...

Python自动化办公应用学习笔记3—— pip工具安装

3.1pip工具安装最常用且最高效的Python第三方库安装方式是采用pip工具安装。pip是Python包管理工具,提供了对Python包的查找、下载、安装、卸载的功能。pip是Python官方提...

Python文件压缩神器:ZipFile功能全解析,支持一键压缩和解压

在Python中处理ZIP文件时,zipfile模块是最常用的工具。它提供了创建、读取、修改ZIP文件的完整功能,无需依赖外部命令。本文将通过核心函数、实战案例和避坑指南,带你掌握这个高效的文件处理模...

取消回复欢迎 发表评论: