网址:www.xservx.com 备案号:蜀ICP备2026035467号-3

python函数有哪些|全面解析函数类型与核心用法

在Python编程中,函数是组织代码的基本单元,是实现模块化、可重用、可维护程序结构的关键。Python提供了丰富多样的函数类型,从基础的内置函数到灵活的自定义函数,再到高效的匿名函数(lambda)和强大的高阶函数,每一种都有其独特应用场景。

掌握python函数有哪些类型及各自特性,是初学者跨越基础门槛、进阶开发者提升代码质量的必经之路。本文将系统梳理Python中常见的函数分类,结合真实代码示例,深入解析其原理、使用技巧与易错点,帮助读者构建完整的函数知识体系。

无论您是正在学习Python的新手,还是希望系统梳理知识体系的开发者,本文都将提供清晰、实用、可落地的参考指南。全文覆盖网民最关注的python函数有哪些相关问题,总计超过3000字深度内容,无冗余信息,专注实用知识。

一、python函数有哪些类型?

Python函数可按不同维度分类,核心类型包括:

  • 内置函数(Built-in Functions):由Python解释器直接提供,无需导入即可使用,如len()、print()、max()等。
  • 自定义函数(User-defined Functions):使用def语句显式定义的函数,是编程中最常见的形式。
  • 匿名函数(Lambda Functions):使用lambda关键字定义的简洁函数,常用于高阶函数的参数。
  • 高阶函数(Higher-order Functions):能接收函数作为参数或返回函数的函数,如map()、filter()、sorted()。
  • 闭包(Closures):嵌套函数中,内部函数引用外部非全局变量形成的函数对象。
  • 装饰器(Decorators):用于动态增强函数功能的高阶函数,本质是返回函数的函数。
  • 生成器函数(Generator Functions):包含yield语句的函数,返回生成器对象,支持惰性计算。

这些类型并非互斥,例如装饰器常用于修饰自定义函数,生成器函数也可作为高阶函数的参数使用。理解分类边界有助于精准选择工具。

二、python内置函数有哪些?常用Top 20详解

Python标准库提供了68个内置函数,覆盖输入输出、类型转换、数学运算、序列操作等场景。以下精选最常用20个,附详细示例:

基础操作
序列处理
类型转换
数学运算

基础操作类

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):将对象输出到标准流。

print("Hello", "World", sep="-", end="!\n")  # 输出:Hello-World!

input([prompt]):从标准输入读取一行并返回字符串。

name = input("请输入姓名:")  # 用户输入后返回字符串

len(s):返回对象(字符串、列表、元组等)的长度或元素个数。

len("Python")  # 6
len([1, 2, 3, 4])  # 4

type(object):返回对象的类型。

type(42)          # 
type([1,2,3])     # 
type(lambda x:x)  # 

序列处理类

max(iterable, *[, key, default]):返回最大值或最大元素。

max([3, 1, 4, 1, 5])          # 5
max(["apple", "banana"], key=len)  # "banana"

min(iterable, *[, key, default]):返回最小值或最小元素。

min(range(10))                # 0
min(["apple", "banana", "kiwi"], key=len)  # "kiwi"

sum(iterable, start=0):对可迭代对象求和(数字类型)。

sum([1, 2, 3, 4])  # 10
sum((1.5, 2.5, 3.0), 10)  # 17.0

sorted(iterable, *, key=None, reverse=False):返回排序后的新列表(原列表不变)。

sorted([3,1,4,1,5])  # [1, 1, 3, 4, 5]
sorted(["c", "a", "b"], key=str.upper, reverse=True)  # ['c', 'b', 'a']

类型转换类

int(x, base=10):将字符串或数字转换为整数。

int("123")      # 123
int("0xFF", 16) # 255
int(3.14)       # 3

float(x):转换为浮点数。

float("3.14")  # 3.14
float(5)       # 5.0

str(obj):将对象转换为字符串表示。

str(123)         # "123"
str([1,2,3])     # "[1, 2, 3]"
str({"a":1})     # "{'a': 1}"

list(x):将可迭代对象转换为列表。

list("abc")       # ['a', 'b', 'c']
list((1,2,3))     # [1, 2, 3]
list(range(3))    # [0, 1, 2]

数学运算类

abs(x):返回绝对值。

abs(-5)    # 5
abs(3+4j)  # 5.0

pow(base, exp[, mod]):幂运算,可选取模。

pow(2, 3)        # 8
pow(2, 3, 5)     # 3 (即 (2^3) % 5 = 8 % 5 = 3)

divmod(a, b):返回商和余数的元组。

divmod(17, 5)  # (3, 2)

round(number[, ndigits]):四舍五入到指定小数位。

round(3.14159, 2)  # 3.14
round(2.5)         # 2 (注意:Python3中采用“银行家舍入法”,.5时取偶数)

三、python函数参数有哪些形式?详解7种参数类型

Python函数参数设计灵活,支持多种类型组合,掌握它们是编写健壮函数的关键。以下为完整分类与示例:

位置参数
关键字参数
默认参数
可变参数
关键字可变参数
仅限关键字参数
参数解包

1. 位置参数(Positional Arguments)

按顺序传递,位置必须匹配。

def greet(name, message):
    return f"{message}, {name}!"
greet("Alice", "Hello")  # "Hello, Alice!"
greet("Hello", "Alice")  # 错误!语义混乱:"Alice, Hello!" → 实际输出为"Alice, Hello!"

⚠️ 注意:位置错误会导致逻辑错误而非语法错误,需谨慎。

2. 关键字参数(Keyword Arguments)

使用参数名传递,顺序可变,提高可读性。

greet(message="Hi", name="Bob")  # "Hi, Bob!"

✅ 优势:避免位置混淆,增强代码可维护性。

3. 默认参数(Default Arguments)

为参数提供默认值,调用时可省略。

def greet(name, message="Hello"):
    return f"{message}, {name}!"
greet("Charlie")              # "Hello, Charlie!"
greet("Charlie", "Hi")        # "Hi, Charlie!"

⚠️ 重要陷阱:默认值只计算一次!若为可变对象(如列表),可能导致状态共享。

def add_item(item, lst=[]):
    lst.append(item)
    return lst
add_item(1)  # [1]
add_item(2)  # [1, 2] ← 非预期!lst被复用

✅ 正确做法:使用None占位。

def add_item(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst

4. 可变位置参数 *args

接收任意数量的位置参数,内部为元组。

def total(*numbers):
    return sum(numbers)
total(1, 2, 3, 4)  # 10

常用于参数数量不定的聚合操作,如日志记录、求和等。

5. 可变关键字参数 **kwargs

接收任意数量的关键字参数,内部为字典。

def info(**details):
    for key, value in details.items():
        print(f"{key}: {value}")
info(name="David", age=30, city="New York")
# name: David
# age: 30
# city: New York

常用于配置项、API参数透传等场景。

6. 仅限关键字参数(Keyword-only Arguments)

通过*分隔,其后的参数必须用关键字传递。

def connect(host, port, *, use_ssl=True):
    return f"{host}:{port}, SSL={use_ssl}"
connect("api.example.com", 443)              # ✅
connect("api.example.com", 443, True)        # ❌ TypeError
connect("api.example.com", 443, use_ssl=True) # ✅

✅ 作用:强制调用者明确指定关键参数,避免误用。

7. 参数解包(Argument Unpacking)

使用*和**将序列/字典解包为参数。

def add(a, b, c):
    return a + b + c
args = [1, 2, 3]
add(*args)  # 6
kwargs = {"a": 1, "b": 2, "c": 3}
add(**kwargs)  # 6

✅ 实用场景:将动态数据(如JSON)直接传递给函数。

四、python匿名函数(lambda)有哪些?何时使用?

lambda是创建小型匿名函数的简洁方式,语法为:lambda 参数: 表达式。它只能包含一个表达式,不能包含语句,常用于高阶函数的临时参数。

基础用法
典型场景
限制与最佳实践

基础语法

等价于定义普通函数:

# 普通函数
def square(x):
    return x * x
# lambda表达式
square = lambda x: x * x
# 调用
print(square(5))  # 25

注意:lambda是表达式而非语句,不能包含多行代码或赋值语句。

典型应用场景

① 配合sorted()排序复杂对象

students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 19},
    {"name": "Charlie", "age": 21}
]
# 按年龄排序
sorted_students = sorted(students, key=lambda x: x["age"])
# 结果:Bob(19), Alice(20), Charlie(21)

② 配合filter()过滤数据

numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))  # [2, 4, 6]

③ 配合map()转换数据

celsius = [0, 20, 37, 100]
fahrenheit = list(map(lambda c: c * 9/5 + 32, celsius))  # [32.0, 68.0, 98.6, 212.0]

④ 作为回调函数

def process_data(data, transform):
    return [transform(x) for x in data]
process_data([1, 2, 3], lambda x: x**2)  # [1, 4, 9]

限制与最佳实践

💡 网友建议:当lambda超过一行或需多次复用时,应改用def定义命名函数。

五、python装饰器(Decorator)有哪些?如何实现?

装饰器是闭包的典型应用,用于在不修改原函数代码的前提下,动态增强函数功能。其本质是接收函数并返回新函数的高阶函数。

基础原理
常用类型
实战示例

基础原理

装饰器结构:外层函数接收被装饰函数,内层函数包装原函数逻辑。

def decorator(func):
    def wrapper(*args, **kwargs):
        print("函数执行前")
        result = func(*args, **kwargs)
        print("函数执行后")
        return result
    return wrapper
@decorator  # 等价于:greet = decorator(greet)
def greet(name):
    return f"Hello, {name}!"
print(greet("Alice"))
# 输出:
# 函数执行前
# Hello, Alice!
# 函数执行后

⚠️ 问题:装饰后函数名变为wrapper,丢失原函数元数据。

常用装饰器类型

① 日志装饰器:记录函数调用信息。

import functools
def log_calls(func):
    @functools.wraps(func)  # 保留原函数元数据
    def wrapper(*args, **kwargs):
        print(f"[LOG] 调用 {func.__name__}({args}, {kwargs})")
        result = func(*args, **kwargs)
        print(f"[LOG] 返回 {result}")
        return result
    return wrapper

② 计时装饰器:测量函数执行时间。

import time
import functools
def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行耗时: {end-start:.4f}s")
        return result
    return wrapper

③ 缓存装饰器(memoization):避免重复计算。

import functools
@functools.lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)
fibonacci(100)  # 快速计算大数

实战:权限验证装饰器

模拟Web后端权限控制:

def require_login(func):
    @functools.wraps(func)
    def wrapper(user, *args, **kwargs):
        if not user.get("is_authenticated"):
            raise PermissionError("请先登录")
        return func(user, *args, **kwargs)
    return wrapper
@require_login
def delete_post(user, post_id):
    print(f"{user['name']} 删除了帖子 {post_id}")
# 测试
user1 = {"name": "Alice", "is_authenticated": True}
user2 = {"name": "Bob", "is_authenticated": False}
delete_post(user1, 123)  # ✅ Alice 删除了帖子 123
delete_post(user2, 456)  # ❌ PermissionError

✅ 优势:业务逻辑与权限控制解耦,复用性强。

六、python函数作用域有哪些?LEGB规则详解

Python变量查找遵循LEGB规则:Local → Enclosing → Global → Built-in。

作用域示例
关键字使用

作用域查找示例

x = "global"  # G
def outer():
    x = "enclosing"  # E
    def inner():
        x = "local"  # L
        print(x)     # 输出 "local"
    inner()
    print(x)       # 输出 "enclosing"
outer()
print(x)         # 输出 "global"

当inner()中无x定义时,会向上查找E→G→B。

关键字使用

nonlocal:修改外层(非全局)变量。

def outer():
    x = "old"
    def inner():
        nonlocal x
        x = "new"
    inner()
    print(x)  # "new"

global:修改全局变量。

x = "global"
def func():
    global x
    x = "modified"
func()
print(x)  # "modified"

⚠️ 注意:过度使用global会破坏模块封装性,应谨慎。

七、python函数文档字符串(Docstring)有哪些规范?

文档字符串(docstring)是函数的元数据,用于自动生成文档和提升可读性。Python社区推荐使用PEP 257规范。

单行文档
多行文档
Sphinx风格

单行文档(Simple Docstrings)

适用于简单函数,用一行描述功能。

def add(a, b):
    """Return the sum of a and b."""
    return a + b

✅ 规范:

多行文档(Multi-line Docstrings)

适用于复杂函数,包含参数、返回值、异常等信息。

def process_data(data, threshold=0.5):
    """
    Process input data by filtering values above threshold.
    Args:
        data (list[float]): Input numerical data.
        threshold (float): Cutoff value (default: 0.5).
    Returns:
        list[float]: Filtered data with values > threshold.
    Raises:
        ValueError: If data contains non-numeric values.
    Examples:
        >>> process_data([0.3, 0.6, 0.8], 0.5)
        [0.6, 0.8]
    """
    if not all(isinstance(x, (int, float)) for x in data):
        raise ValueError("data must contain only numbers")
    return [x for x in data if x > threshold]

Sphinx风格(推荐)

广泛用于开源项目,支持自动生成API文档:

def calculate_area(radius):
    """Calculate the area of a circle.
    :param radius: The radius of the circle.
    :type radius: float
    :returns: Area of the circle.
    :rtype: float
    :raises ValueError: If radius is negative.
    :Example:
    >>> calculate_area(1)
    3.141592653589793
    """
    if radius < 0:
        raise ValueError("radius must be non-negative")
    return 3.141592653589793 * radius ** 2

💡 实用建议:所有公开API必须包含docstring,内部函数至少单行描述。

八、python函数编写最佳实践有哪些?

基于社区经验总结的高效函数设计原则:

函数设计
代码风格
测试与调试

函数设计原则

代码风格规范

# 低效写法
def process(user):
    if user:
        if user.is_active:
            if user.has_permission:
                return user.data
    return None
# 优化写法
def process(user):
    if not user or not user.is_active or not user.has_permission:
        return None
    return user.data

测试与调试建议

💡 示例:使用@functools.wraps保留元数据,便于测试时识别函数。

总结:python函数有哪些?核心知识图谱

通过本文系统梳理,python函数有哪些类型已清晰呈现:

  1. 基础分类:内置函数、自定义函数、匿名函数、高阶函数、闭包、装饰器、生成器函数
  2. 参数设计:位置参数、关键字参数、默认参数、*args、**kwargs、仅限关键字参数、参数解包
  3. 作用域规则:LEGB原则(Local→Enclosing→Global→Built-in)与nonlocal/global关键字
  4. 文档规范:PEP 257单行/多行文档与Sphinx风格
  5. 最佳实践:单一职责、参数控制、命名规范、类型注解、错误处理

掌握这些知识后,即可编写出高效、可维护、符合Python风格的代码。建议结合实际项目反复练习,逐步内化为编程本能。

附录:常用内置函数速查表

函数功能说明典型示例
abs(x)绝对值abs(-5) → 5
all(iterable)所有元素为真则返回Trueall([1,2,3]) → True
any(iterable)任一元素为真则返回Trueany([0,1,2]) → True
enumerate(iterable)返回枚举对象list(enumerate(['a','b'])) → [(0,'a'),(1,'b')]
filter(func, iterable)过滤元素list(filter(lambda x:x>0, [-1,2,-3])) → [2]
globals()返回全局符号表字典g = globals()
hasattr(obj, name)检查对象是否有属性hasattr(str, 'upper') → True
id(obj)返回对象唯一标识id(42) → 140245120232800
isinstance(obj, class)检查对象类型isinstance(5, int) → True
map(func, iterable)映射函数list(map(str, [1,2])) → ['1','2']
open(file, mode)打开文件with open('test.txt') as f: ...
range(start, stop, step)生成整数序列list(range(2,8,2)) → [2,4,6]
repr(obj)返回对象官方字符串表示repr("hi") → "'hi'"
reversed(seq)返回反转迭代器list(reversed([1,2,3])) → [3,2,1]
setattr(obj, name, value)设置对象属性setattr(obj, 'x', 10)
slice(start, stop, step)创建切片对象list('abcde')[slice(1,4)] → ['b','c','d']
zip(*iterables)聚合元素list(zip([1,2], ['a','b'])) → [(1,'a'),(2,'b')]