# 动态类型演示
a = 10 # 整型
a = 3.14 # 浮点型
a = "Python" # 字符串
a = [1, 2, 3] # 列表
# 格式化输出进阶
name = "Alice"
print(f"{name:*^20}") # 居中填充输出:******Alice*******
# 常见运算符优先级练习
result = 5 + 3 * 2 ** 2 // (4 % 3)
print(result) # 输出:11
# 列表推导式+条件过滤
matrix = [[i*j for j in range(1,6) if j%2==0] for i in range(1,4)]
# 输出:[[2, 4], [4, 8], [6, 12]]
# 切片技巧
nums = list(range(10))
print(nums[::2]) # 步长2:0,2,4,6,8
print(nums[::-1]) # 逆序输出
# 字典推导式+嵌套字典
students = {
name: {"math": random.randint(60,100),
"english": random.randint(60,100)}
for name in ["Alice", "Bob", "Charlie"]
}
# 字典合并(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2 # {'a':1, 'b':3, 'c':4}
# 带参数的装饰器
def retry(max_attempts=3):
def decorator(func):
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {attempt+1} failed: {e}")
raise RuntimeError("All attempts failed")
return wrapper
return decorator
@retry(max_attempts=5)
def risky_operation():
# 可能失败的操作
# 协程实现数据管道
def data_pipeline():
while True:
data = yield
data = data.strip().upper()
yield f"Processed: {data}"
pipe = data_pipeline()
next(pipe) # 激活协程
print(pipe.send(" hello ")) # Processed: HELLO
# 属性描述符
class PositiveNumber:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
return instance.__dict__[self.name]
def __set__(self, instance, value):
if value <= 0:
raise ValueError("必须为正数")
instance.__dict__[self.name] = value
class Product:
price = PositiveNumber()
quantity = PositiveNumber()
def __init__(self, price, quantity):
self.price = price
self.quantity = quantity
# 自动注册子类
class PluginMeta(type):
_plugins = {}
def __new__(cls, name, bases, attrs):
new_class = super().__new__(cls, name, bases, attrs)
if "plugin_id" in attrs:
cls._plugins[attrs["plugin_id"]] = new_class
return new_class
class Plugin(metaclass=PluginMeta):
pass
class PDFExport(Plugin):
plugin_id = "pdf"
# 异步上下文管理器
class AsyncDatabaseConnection:
async def __aenter__(self):
self.conn = await asyncpg.connect()
return self.conn
async def __aexit__(self, exc_type, exc, tb):
await self.conn.close()
# 使用示例
async with AsyncDatabaseConnection() as conn:
await conn.execute("SELECT ...")
from typing import TypeVar, Generic
T = TypeVar('T')
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: list[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
# 使用argparse开发专业CLI
import argparse
def create_parser():
parser = argparse.ArgumentParser(
description="高级文件处理工具",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("paths", nargs="+", help="要处理的文件路径")
parser.add_argument("-o", "--output",
help="输出目录", default="./output")
parser.add_argument("--verbose", action="store_true",
help="显示详细输出")
return parser
if __name__ == "__main__":
parser = create_parser()
args = parser.parse_args()
# 处理逻辑
my_project/
├── src/
│ ├── core/
│ │ ├── __init__.py
│ │ ├── processors.py
│ │ └── utils.py
│ └── cli.py
├── tests/
│ ├── test_core.py
│ └── conftest.py
├── setup.py
├── requirements.txt
└── README.md
# 使用tracemalloc分析内存
import tracemalloc
tracemalloc.start()
# 执行需要分析的代码
data = [bytearray(1024) for _ in range(100000)]
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics("lineno")[:5]:
print(stat)
# 使用Cython加速计算
# math_ops.pyx
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
def sum_squares(double[:] arr):
cdef double total = 0.0
cdef int i
for i in range(arr.shape[0]):
total += arr[i] ** 2
return total
成长建议:
通过系统化学习路径+刻意练习,可在6个月内达到高级Python开发者水平。建议现在开始第一个实战项目,在实践中深化理解!