Python中的函数是执行特定任务的代码块,具有可重用性和模块化的特点。以下是Python函数的一些基础概念和用法:
1. **定义函数**:
使用`def`关键字后跟函数名和括号内的参数列表来定义函数。
```python
def my_function(param1, param2):
# 函数体
return param1 + param2
```
2. **调用函数**:
通过函数名和括号内的参数来调用函数。
```python
result = my_function(5, 10)
```
3. **参数和返回值**:
函数可以接收参数,并使用`return`关键字返回值。
4. **默认参数值**:
在定义函数时,可以为参数指定默认值。
```python
def greet(name, message="Hello"):
return f"{message}, {name}!"
```
5. **可变参数**:
使用星号(`*`)定义可变数量的位置参数,使用双星号(`**`)定义可变数量的关键字参数。
```python
def make_pizzas(*toppings):
print("Making pizza with the following toppings:")
for topping in toppings:
print(f" - {topping}")
make_pizzas('mushrooms', 'green peppers', 'extra cheese')
```
6. **函数注解**:
使用注解可以指定函数参数的类型和返回值的类型,有助于代码的可读性和静态类型检查。
```python
def divide(x: float, y: float) -> float:
return x / y
```
7. **作用域**:
Python中的变量有自己的作用域,包括局部(local)、嵌套(enclosed)和全局(global)。
8. **闭包**:
闭包是定义在函数内部的函数,可以记住并访问外部函数的作用域。
```python
def outer_function(x):
def inner_function():
print(x)
return inner_function
result = outer_function(5)
result() # 输出 5
```
9. **装饰器**:
装饰器是Python中的一个高级功能,用于修改或增强函数的行为。
```python
def my_decorator(func):
def wrapper():
print("Something is happening before the function is called.")
func()
print("Something is happening after the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
```
10. **匿名函数(Lambda)**:
使用`lambda`关键字可以创建匿名函数,通常用于需要简短函数的地方。
```python
add = lambda x, y: x + y
print(add(5, 3)) # 输出 8
```
11. **生成器**:
使用`yield`关键字可以创建生成器,它是一种特殊的迭代器,用于惰性计算。
```python
def count_up_to(max):
count = 1
while count <= max:
yield count
count += 1
for number in count_up_to(5):
print(number)
```
Python的函数功能非常强大,支持多种编程范式,包括面向对象、函数式编程等。函数是Python编程中不可或缺的一部分,掌握函数的使用对于编写高效、可维护的代码至关重要。