这篇文章介绍了一些python的进阶用法。适用于刚掌握python基础的同学(大佬请回避)。可能不全,但会持续更新。ps:如果你觉得有需要补充的部分,欢迎留言。
目录
1. 推导式(Comprehensions)
是什么:推导式是 Python 中一种简洁的语法,用于快速创建列表、字典或集合。
为什么:避免冗长的 for
循环,使代码更简洁、易读。
(1) 列表推导式
基本语法:
[ 表达式 for 变量 in 可迭代对象 if 条件 ]
示例1:生成平方列表
# 传统方式
squares = []
for x in range(10):
squares.append(x**2)
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 列表推导式
squares = [x**2 for x in range(10)]
print(squares) # 同上,但代码更简洁
示例2:带条件的推导式
# 只保留偶数的平方
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # 输出: [0, 4, 16, 36, 64]
当然条件语句也可以更复杂:
# 偶数计算平方,奇数不变
even_squares = [x**2 if x % 2 == 0 else x for x in range(10)]
print(even_squares) # 输出: [0, 1, 4, 3, 16, 5, 36, 7, 64, 9]
注意:对比两种条件推导式发现,if语句可以写在for语句之前,也可以写在其后。
(2) 字典推导式
基本语法:
{ 键表达式: 值表达式 for 变量 in 可迭代对象 if 条件 }
示例:将列表转换为字典
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(fruit_lengths) # 输出: {'apple': 5, 'banana': 6, 'cherry': 6}
(3) 集合推导式
基本语法:
{ 表达式 for 变量 in 可迭代对象 if 条件 }
示例:去重并生成集合
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_squares = {x**2 for x in numbers}
print(unique_squares) # 输出: {1, 4, 9, 16, 25}
2. 生成器(Generators)
是什么:生成器是一种“惰性计算”的迭代器,逐步生成值,不一次性占用内存。
为什么:处理大数据时节省内存,或在需要时生成无限序列。
(1) 生成器函数:使用 yield
示例:生成斐波那契数列
def fibonacci():
a, b = 0, 1
while True:
yield a # 每次调用 next() 时返回 a,并暂停在这里
a, b = b, a + b
# 使用生成器
fib = fibonacci()
print(next(fib)) # 输出: 0
print(next(fib)) # 输出: 1
print(next(fib)) # 输出: 1
print(next(fib)) # 输出: 2
(2) 生成器表达式
语法:类似列表推导式,但用 ()
包裹。
squares_gen = (x**2 for x in range(10))
print(next(squares_gen)) # 输出: 0
print(next(squares_gen)) # 输出: 1
print(next(squares_gen)) # 输出: 4
print(next(squares_gen)) # 输出: 9
3. 匿名函数(Lambda 函数)
是什么:没有名字的简单函数,用 lambda
关键字定义。
为什么:简化代码,特别适合需要临时函数的场景。
示例1:基本用法
# 定义匿名函数:计算两数之和
add = lambda x, y: x + y
print(add(3, 5)) # 输出: 8
print(add(10, 20)) # 输出: 30
示例2:结合 sorted
排序
students = [("Alice", 90), ("Bob", 80), ("Charlie", 85)]
# 按分数排序(使用匿名函数指定排序依据)
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students) # 输出: [('Bob', 80), ('Charlie', 85), ('Alice', 90)]
4. *
的用法
是什么:*
在 Python 中有多种用途,包括解包、可变参数等。
*
用于解包可迭代对象(如列表、元组),**
用于解包字典。
(1) 解包操作
示例1:解包列表/元组
def add(a, b, c):
return a + b + c
numbers_list = [1, 2, 3]
numbers_tuple = (1, 2, 3)
result1 = add(*numbers_list) # 相当于 add(1, 2, 3)
result2 = add(*numbers_tuple)
print(result1) # 输出: 6
print(result2) # 输出: 6
示例2:解包字典
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
person = {"name": "Alice", "age": 25}
greet(**person) # 相当于 greet(name="Alice", age=25)
# 输出: Hello Alice, you are 25 years old.
示例3:混合解包
def func(a, b, c, d):
print(a, b, c, d)
args = [1, 2]
kwargs = {"c": 3, "d": 4}
func(*args, **kwargs) # 输出: 1 2 3 4
(2) 函数定义中的 *args
和 **kwargs
*args
用于接收任意数量的位置参数,**kwargs
用于接收任意数量的关键字参数。
示例1: 接收任意数量的位置参数
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3)) # 输出: 6
示例2:接收任意数量的关键字参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
# 输出:
# name: Alice
# age: 25
混合使用:
def func(a, b, *args, **kwargs):
print(f"a={a}, b={b}, args={args}, kwargs={kwargs}")
func(1, 2, 3, 4, x=10, y=20)
# 输出: a=1, b=2, args=(3, 4), kwargs={'x': 10, 'y': 20}
(3)模块导入中的 *
*
用于控制 from module import *
时导入的内容,通过定义 __all__
变量来指定允许导出的符号。
定义 __all__:
# mymodule.py
__all__ = ["public_func", "PUBLIC_VAR"] # 指定允许通过 * 导入的内容
def public_func():
print("This is a public function.")
def _private_func():
print("This is a private function.")
PUBLIC_VAR = 100
_PRIVATE_VAR = 200
使用 from mymodule import *
from mymodule import *
public_func() # 正常调用
print(PUBLIC_VAR) # 正常输出: 100
_private_func() # 报错: NameError(未导入)
print(_PRIVATE_VAR) # 报错: NameError
(4)其他用法
示例1:合并字典
dict1 = {"a": 1, "b": 2}
dict2 = {"c": 3, "d": 4}
merged = {**dict1, **dict2}
print(merged) # 输出: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
示例2:链式函数调用
def step1(a, b):
return a + b
def step2(c, d):
return c * d
result = step2(*step1(2, 3), 4) # 先计算 step1(2,3)=5,然后 step2(5,4)=20
print(result) # 输出: 20
5. 装饰器(Decorators)
是什么:装饰器是一个函数,用于修改其他函数的行为。
为什么:在不修改原函数代码的前提下,添加新功能(如日志、计时等)。
示例1:基础装饰器
def my_decorator(func):
def wrapper():
print("Before function call")
func() # 执行原函数
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# Before function call
# Hello!
# After function call
装饰器的实际作用:
装饰器 @my_decorator 的作用是:将 say_hello 函数替换为 my_decorator(say_hello) 的返回值。
具体来说:调用 say_hello() 时,实际上调用的是 wrapper()。
等效代码:
装饰器的作用可以理解为以下代码:
def my_decorator(func):
def wrapper():
print("Before function call")
func() # 执行原函数
print("After function call")
return wrapper
def say_hello():
print("Hello!")
# 手动应用装饰器
say_hello = my_decorator(say_hello)
# 调用装饰后的函数
say_hello()
示例2:带参数的装饰器
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# 输出:
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!
6. 魔法方法(Magic Methods)
是什么:以双下划线 __
开头和结尾的特殊方法,用于定义类的行为。
为什么:让自定义的类支持 Python 内置操作(如 +
、print()
等)。
示例1:__str__
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age} years old)"
p = Person("Alice", 25)
print(p) # 输出: Alice (25 years old)
示例2:__add__
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3.x, v3.y) # 输出: 4 6
7. 迭代器(Iterators)
是什么:实现了 __iter__()
和 __next__()
方法的对象,用于遍历数据。
为什么:让自定义对象支持 for
循环。
示例:自定义迭代器
class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self # 返回迭代器对象本身
def __next__(self):
if self.current <= 0:
raise StopIteration
else:
self.current -= 1
return self.current + 1
for num in CountDown(5):
print(num) # 输出: 5, 4, 3, 2, 1
8. 上下文管理器(Context Managers)
是什么:通过 with
语句管理资源(如文件、网络连接),自动处理初始化和清理。
为什么:避免资源泄漏(如忘记关闭文件)。
示例1:使用 with
管理文件
with open("test.txt", "w") as f:
f.write("Hello, World!")
# 文件会自动关闭,无需手动调用 f.close()
示例2:自定义上下文管理器
class Timer:
def __enter__(self):
import time
self.start = time.time()
def __exit__(self, exc_type, exc_val, exc_tb):
import time
print(f"Time elapsed: {time.time() - self.start:.2f}s")
with Timer():
# 执行一些耗时操作
sum(range(1000000)) # 计算 0 到 999,999 的和
# 输出: Time elapsed: 0.01s
9. 闭包(Closures)
欢迎移步我的另一篇文章(更详细的讲解):Python闭包
是什么:内部函数捕获并保存外部函数的变量。
为什么:用于创建有状态的函数。
示例:计数器
def counter():
count = 0
def increment():
nonlocal count # 声明 count 不是局部变量
count += 1
return count
return increment
c = counter()
print(c()) # 输出: 1
print(c()) # 输出: 2
10.元类(Metaclasses)
是什么:元类是类的类,控制类的创建行为。
为什么:用于高级框架设计(如 Django 的 ORM)。
欢迎移步我的另一篇文章(更详细的讲解):Python 元类
示例:简单元类
class Meta(type):
def __new__(cls, name, bases, dct):
print(f"Creating class {name}")
return super().__new__(cls, name, bases, dct)
class MyClass(metaclass=Meta):
pass
# 输出: Creating class MyClass
11.异常捕获
欢迎移步我的另一篇文章(更详细的讲解):Python异常(Bug)捕获与处理