Table of Contents
四、 函数
Python 提供了多种函数特性,使得代码更加简洁、灵活和可重用。以下是对函数的参数和默认值、可变参数、返回值、作用域、匿名函数、函数注解、装饰器、递归函数、闭包和生成器的详细介绍。
1.参数和默认值
函数可以接受多个参数,并且可以为参数指定默认值。
def greet(name, greeting="Hello"): return f"{greeting}, {name}!"print(greet("Alice"))print(greet("Bob", "Hi")) # 输出: Hi, Bob! # 输出: Hello, Alice!2.可变参数
Python 支持可变参数,可以用来处理不确定数量的参数。
*args (位置参数)
def sum_all(*args): return sum(args)print(sum_all(1, 2, 3, 4)) # 输出: 10**kwargs (关键字参数)
def print_info(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}")print_info(name="Alice", age=30, city="New York"# 输出:# name: Alice# age: 30# city: New York3. 返回值
函数可以返回一个值或多个值。用 return 语句返回。
def add(a, b): return a + bprint(add(5, 3)) # 输出: 8def get_name_and_age(): return "Alice", 30name, age = get_name_and_age()print(name, age) # 输出: Alice 304. 作用域
在Python中,变量的作用域决定了变量在程序中的可见性和生命周期。主要有以下几种作用域:
(1)局部作用域(Local Scope):
-
局部作用域是指变量在函数内部定义,只在该函数内部可见。
-
当函数执行完毕后,这些变量将被销毁。
def my_function(): local_var = 'I am local' print(local_var)my_function() # 输出: I am local# print(local_var) # 这会抛出错误,因为local_var不在全局作用域(2)嵌套作用域(Enclosing Scope):
- 如果一个函数定义在另一个函数内部,那么内部函数可以访问外部函数的变量,这称为嵌套作用域。
def outer_function(): def inner_function(): print(inner_local_var) # 可以访问外部函数的局部变量 inner_local_var = 'I am in the outer function' inner_function()outer_function() # 输出: I am in the outer function(3)全局作用域(Global Scope):
-
全局作用域是指在所有函数外部定义的变量,它们在整个模块中都是可见的。
-
要在一个函数内部访问全局变量,需要使用global关键字声明。
global_var = 'I am global' def my_function(): global global_var # 声明global_var为全局变量 global_var = 'Global variable changed'my_function()print(global_var) # 输出: Global variable changed(4)内建作用域(Built-in Scope):
-
内建作用域包含了Python内置的名称,如函数print()、len()等,以及内置变量如__name__。
-
这些名称和变量是Python解释器提供的,可以在任何作用域中使用,无需声明。
print(len('Hello, World!')) # 使用内建函数len(),属于内建作用域(5)类作用域(Class Scope):
类作用域是指在类定义中定义的变量,这些变量是类的属性,可以在类的任何方法中访问。
class MyClass: class_var = 'I am a class variable' def my_method(self): print(self.class_var)obj = MyClass()obj.my_method() # 输出: I am a class variable(6)模块作用域(Module Scope):
模块作用域是指在模块(文件)中定义的变量,这些变量可以在模块的任何函数中访问,但模块外部不可见。
module_var = 'I am a module variable'def my_function(): print(module_var)my_function() # 输出: I am a module variable# 当这个模块被另一个模块导入时,my_function仍然可以访问module_var5. 匿名函数(Lambda 函数)
Lambda 函数是小的匿名函数,可以有任意数量的参数,但只能有一个表达式。
square = lambda x: x ** 2print(square(5)) # 输出: 25add = lambda x, y: x + yprint(add(3, 5)) # 输出: 86. 函数注解
Python中的函数注解(Function Annotations)是一种添加到函数参数和返回值的元数据,用于说明参数和返回值的类型。函数注解在Python 3.0中引入,它们不强制类型检查,但可以提供额外的文档信息,帮助开发者理解函数应该如何使用。
函数注解的作用
-
文档目的:注解可以作为文档的一部分,帮助开发者理解函数期望接收什么类型的参数以及它将返回什么类型的值。
-
类型检查工具:虽然Python是动态类型语言,但可以使用像mypy这样的静态类型检查工具来检查函数注解的一致性。
-
IDE支持:现代的集成开发环境(IDE)和代码编辑器可以使用注解来提供自动完成、类型检查和重构支持。
-
装饰器和框架:某些Python框架和装饰器可能会使用函数注解来实现特定的功能,例如自动将函数参数与请求数据绑定。
def add(x: int, y: int) -> int: return x + yprint(add(5, 3)) # 输出: 8print(add.__annotations__) # 输出: {'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>}7. 装饰器
装饰器是一种高级的函数,用于在不修改函数定义的前提下,扩展函数的功能。
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_decoratordef say_hello(): print("Hello!")
say_hello()# 输出:# Something is happening before the function is called.# Hello!# Something is happening after the function is called.8. 递归函数
递归函数是指在函数中调用函数自身。
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1)print(factorial(5)) # 输出: 1209. 闭包
闭包是指函数内部的函数可以引用外部函数的局部变量。
def outer_func(x): def inner_func(y): return x + y return inner_func
add_five = outer_func(5)print(add_five(10)) # 输出: 1510. 生成器
生成器是使用 yield 关键字的函数,返回一个可以迭代的生成器对象。
def generate_numbers(): for i in range(5): yield i
for number in generate_numbers(): print(number)# 输出:# 0# 1# 2# 3# 4以上是 Python 函数的各种特性和使用方法的详细介绍。这些特性使得 Python 函数强大且灵活,适用于各种编程场景。
五、异常处理
在 Python 中,异常处理用于处理程序运行过程中可能发生的错误或异常情况,以避免程序崩溃并提供更友好的错误处理方式。以下是 Python 中与异常处理相关的功能的详细介绍。
1.基本的异常处理
异常处理使用 try-except 语句来捕获和处理异常。
try: # 可能发生异常的代码 result = 10 / 0except ZeroDivisionError: # 处理异常的代码 print("Error: Division by zero!")2.捕获多个异常
可以在一个 except 子句中捕获多个异常,或者使用多个 except 子句分别捕获不同的异常。
try: result = 10 / 0except (ZeroDivisionError, TypeError) as e: print(f"Error: {e}")try: result = 10 / "a"except ZeroDivisionError: print("Error: Division by zero!")except TypeError: print("Error: Type error!")3.捕获所有异常
使用 except 子句而不指定异常类型,可以捕获所有类型的异常。但不推荐使用这种方式,因为它可能会掩盖程序中的其他错误。
try: result = 10 / 0except: print("An error occurred!")4.获取异常信息
可以使用 as 关键字获取异常对象,从而访问异常的详细信息。
try: result = 10 / 0except ZeroDivisionError as e: print(f"Error: {e}")5.else 子句
else 子句在没有发生异常时执行
try: result = 10 / 2except ZeroDivisionError: print("Error: Division by zero!")else: print(f"Result: {result}")6.finally 子句
finally 子句中的代码无论是否发生异常都会执行,通常用于资源清理工作。
try: result = 10 / 2except ZeroDivisionError: print("Error: Division by zero!")else: print(f"Result: {result}")finally: print("This will always be executed.")7.自定义异常
可以通过继承内置的 Exception 类来创建自定义异常。
```pythonclass CustomError(Exception): pass
try: raise CustomError("This is a custom error")except CustomError as e: print(e)8.抛出异常
使用 raise 关键字可以显式地引发异常。
def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero") return a / b
try: divide(10, 0)except ValueError as e: print(e)9.断言(assert)
assert 语句用于检查一个条件,如果条件为假,则引发 AssertionError 异常。
def divide(a, b): assert b != 0, "Cannot divide by zero" return a / b
try: divide(10, 0)except AssertionError as e: print(e)10.上下文管理器和 with 语句
with 语句用于简化资源管理,可以自动处理异常并确保资源的正确释放。
with open('file.txt', 'r') as file: content = file.read()
# 相当于file = open('file.txt', 'r')try: content = file.read()finally: file.close()11.上下文管理器类
可以通过实现 enter 和 exit 方法来自定义上下文管理器。
class MyContext: def __enter__(self): print("Entering context") return self
def __exit__(self, exc_type, exc_value, traceback): print("Exiting context") if exc_type is not None: print(f"An exception occurred: {exc_value}") return True # Suppresses the exception
with MyContext(): print("Inside the context") raise ValueError("An error")输出:
Entering contextInside the contextExiting contextAn exception occurred: An error12.异常链
通过 raise … from … 语句可以将新的异常与先前的异常链接起来,保留异常链。
try: 1 / 0except ZeroDivisionError as e: raise ValueError("A value error occurred") from e13.自定义 str 和 repr 方法
可以通过自定义异常类的 str 和 repr 方法来提供更详细的异常信息。
class CustomError(Exception): def __init__(self, message, code): super().__init__(message) self.code = code
def __str__(self): return f"{self.args[0]} (code: {self.code})"
try: raise CustomError("This is a custom error", 404)except CustomError as e: print(e)输出:
This is a custom error (code: 404)相关文章
Python基础(一)分类:教程
面向初学者的python入门教程
Python基础(三)分类:教程
面向初学者的python入门教程
使用cline搭建python的AI编程环境分类:教程
介绍使用cline搭建python的AI编程环境