python 函数定义

来源:undefined 2025-05-26 03:09:04 1001

在Python中,函数是组织好的一段代码,可以重复使用。它们可以接受输入(参数),可以返回输出。函数是通过 def 关键字来定义的。定义一个函数的一般格式如下:

def function_name(parameters): """ 文档字符串(可选),用于描述函数的用途。 """ 函数体 return value

1. 定义函数

函数可以没有参数,也可以有一个或多个参数。在函数定义时,参数是在函数名后面的括号中指定的。以下是一个简单的示例:

def greet(): """打印问候语。""" print("Hello, World!")

在上面的例子中,greet 是一个没有参数的简单函数。调用时,它将打印“Hello, World!”。

另一个带参数的例子:

def greet_user(name): """使用名称向用户问好。""" print(f"Hello, {name}!")

greet_user 函数接受一个参数 name,调用时需要提供这个参数值。例如:

greet_user("Alice")

将输出 Hello, Alice!。

2. 返回值的函数

函数不仅可以执行一些操作,还可以返回一个值,这是通过 return 语句实现的。以下是一个示例:

def add_numbers(a, b): """返回两个数的和。""" return a + b

调用此函数时,可以使用返回值:

result = add_numbers(3, 5) print(result) # 输出 8

3. 默认参数值

在函数定义中,你可以为参数指定默认值。如果调用函数时没有提供该参数的值,则使用默认值:

def greet_user(name="Guest"): """使用名称向用户问好,如果未提供名称,则默认为 Guest。""" print(f"Hello, {name}!")

这样,greet_user() 没有参数时,将输出 Hello, Guest!。

4. 关键字参数

关键字参数允许在调用函数时显式指定参数名,以便函数可以根据名称应用这些值:

def describe_pet(animal_type, pet_name): """显示宠物信息。""" print(f" I have a {animal_type}.") print(f"My {animal_type}s name is {pet_name}.")

调用函数时,可以按照需要的顺序传递参数,或使用关键字参数改变顺序:

describe_pet(animal_type=hamster, pet_name=Harry) describe_pet(pet_name=Willie, animal_type=dog)

5. 参数的任意数量

有时候,需要一个函数可以接受任意数量的参数,这时可以使用 *args 和 kwargs。*args 用于收集任意数量的非关键字参数,kwargs 用于收集任意数量的关键字参数。

def make_pizza(size, *toppings): """概述要制作的披萨。""" print(f" Making a {size}-inch pizza with the following toppings:") for topping in toppings: print(f"- {topping}")

调用此函数可以传递多个参数:

make_pizza(16, pepperoni) make_pizza(12, mushrooms, green peppers, extra cheese)

对于关键字参数使用:

def build_profile(first, last, user_info): """创建一个字典,其中包含我们知道的有关用户的一切。""" profile = {first_name: first, last_name: last} for key, value in user_info.items(): profile[key] = value return profile user_profile = build_profile(albert, einstein, location=princeton, field=physics) print(user_profile)

6. 文档字符串

文档字符串(通常是 docstring)是定义函数时用三引号包围的字符串,用以描述函数的作用以及其参数。help(function_name) 可以查看函数的文档:

def square(number): """返回一个数的平方。""" return number 2 print(help(square))

7. 高级函数概述

匿名函数(Lambda 函数): 使用 lambda 关键字创建的小型匿名函数。它们可以接受多个参数,但只能有一个表达式。语法:lambda parameters: expression。

square = lambda x: x * x print(square(5)) # -> 25

闭包(Closure): 在一个外函数中定义,并返回一个内函数,同时在返回时记住环境中的一些变量。

def make_multiplier(x): def multiplier(n): return x * n return multiplier times3 = make_multiplier(3) print(times3(10)) # -> 30

装饰器(Decorator): 一个装饰器是一个函数,用于修改另一个函数的行为。通常通过高阶函数实现:

def decorator_function(original_function): def wrapper_function(*args, kwargs): print(f"Wrapper executed this before {original_function.__name__}") return original_function(*args, kwargs) return wrapper_function @decorator_function def display(): print("Display function ran") display()

总结

函数是编程中非常重要的构造块,它们使代码更简洁、可重用和易于阅读。通过掌握函数定义及其各种特性,如参数、返回值、闭包和装饰器等,程序员可以编写高效和模块化的代码。无论是简单的还是复杂的项目,函数都无疑是Python开发必不可少的部分。

上一篇:pg数据库是国产的吗 下一篇:mysql分库

最新文章