小學(xué)生必須掌握的Python語(yǔ)法與代碼示例
學(xué)習(xí)Python從入門到精通,關(guān)鍵在于先建立扎實(shí)的核心概念(如基礎(chǔ)語(yǔ)法、函數(shù)、面向?qū)ο螅?,再系統(tǒng)掌握其高級(jí)特性和生態(tài)工具。下面我為你規(guī)劃了一條清晰的學(xué)習(xí)路徑,并提供了核心知識(shí)框架和示例。
?? 第一階段:基礎(chǔ)核心
這個(gè)階段的目標(biāo)是學(xué)會(huì)用Python表達(dá)基本邏輯和操作數(shù)據(jù)。
- 基礎(chǔ)語(yǔ)法與環(huán)境
- 核心:理解變量、基本數(shù)據(jù)類型(整型、浮點(diǎn)型、布爾型)、運(yùn)算符和注釋。
- 示例:快速體驗(yàn)Python的交互模式。
# 變量與運(yùn)算
price = 19.95
quantity = 3
total = price * quantity
print(f"總價(jià): {total}") # 輸出: 總價(jià): 59.85
# 類型轉(zhuǎn)換與檢查
num_str = "123"
num_int = int(num_str)
print(isinstance(num_int, int)) # 輸出: True- 核心數(shù)據(jù)結(jié)構(gòu)
- Python的強(qiáng)大很大程度上源于其靈活的內(nèi)置數(shù)據(jù)結(jié)構(gòu)。下表對(duì)比了它們的關(guān)鍵特性:
| 類型 | 可變性 | 是否有序 | 元素要求 | 典型用途與示例 |
|---|---|---|---|---|
| 列表(List) | 可變 | 有序 | 可重復(fù),任意類型 | 存儲(chǔ)有序序列,內(nèi)容可增刪改。tasks = ['寫報(bào)告', '開會(huì)', 1] |
| 元組(Tuple) | 不可變 | 有序 | 可重復(fù),任意類型 | 存儲(chǔ)不可變序列,常用于保證數(shù)據(jù)安全或作為字典鍵。point = (10, 20) |
| 字典(Dict) | 可變 | 無序(按key存取) | Key不可重復(fù)且不可變 | 存儲(chǔ)鍵值對(duì),實(shí)現(xiàn)快速查詢。student = {'name': '小明', 'score': 90} |
| 集合(Set) | 可變 | 無序 | 不可重復(fù) | 去重、集合運(yùn)算(交集、并集)。unique_numbers = {1, 2, 2, 3} # 結(jié)果{1, 2, 3} |
示例:列表和字典的常用操作。
# 列表操作
fruits = ['apple', 'banana']
fruits.append('orange') # 增加
fruits[1] = 'grape' # 修改
last_fruit = fruits.pop() # 刪除并返回最后一個(gè)元素
print(fruits) # 輸出: ['apple', 'grape']
# 字典操作
scores = {'Math': 85, 'English': 92}
scores['Science'] = 88 # 增加鍵值對(duì)
print(scores['Math']) # 通過key訪問: 85
for subject, score in scores.items(): # 遍歷
print(f"{subject}: {score}")- 程序流程控制
- 核心:使用
if-elif-else進(jìn)行條件分支,用for和while進(jìn)行循環(huán),并用try-except處理異常。 - 示例:結(jié)合數(shù)據(jù)結(jié)構(gòu)的綜合流程控制。
- 核心:使用
# 條件與循環(huán)處理考試成績(jī)
grade_dict = {'張三': 78, '李四': 92, '王五': 58}
for name, score in grade_dict.items():
if score >= 90:
level = '優(yōu)秀'
elif score >= 60:
level = '及格'
else:
level = '不及格'
print(f"{name}: {score}分 -> {level}")
# 異常處理
try:
user_input = int(input("請(qǐng)輸入一個(gè)數(shù)字: "))
result = 100 / user_input
except ValueError:
print("輸入的不是有效數(shù)字!")
except ZeroDivisionError:
print("除數(shù)不能為零!")
else:
print(f"結(jié)果是: {result}")?? 第二階段:進(jìn)階核心
掌握如何組織代碼、抽象問題,并處理外部數(shù)據(jù)。
- 函數(shù)與代碼復(fù)用
- 核心:使用
def定義函數(shù),理解參數(shù)傳遞(位置參數(shù)、默認(rèn)參數(shù)、可變參數(shù)*args和關(guān)鍵字參數(shù)**kwargs),以及變量作用域。 - 關(guān)鍵點(diǎn):Python中,不可變對(duì)象(如整數(shù)、字符串、元組)是“按值傳遞”(實(shí)際是傳遞對(duì)象的引用,但無法修改原對(duì)象),可變對(duì)象(如列表、字典)是“按引用傳遞”(在函數(shù)內(nèi)修改會(huì)影響原對(duì)象)。
- 核心:使用
- 示例:
# 定義帶默認(rèn)參數(shù)和類型提示的函數(shù)
def greet(name: str, greeting: str = "Hello") -> str:
"""返回一個(gè)問候字符串。"""
return f"{greeting}, {name}!"
print(greet("Alice")) # 使用默認(rèn)參數(shù)
print(greet("Bob", "Hi")) # 提供參數(shù)
# 可變參數(shù)示例:計(jì)算任意個(gè)數(shù)的和
def dynamic_sum(*args, **kwargs):
normal_sum = sum(args)
print(f"位置參數(shù)和: {normal_sum}")
print(f"關(guān)鍵字參數(shù): {kwargs}")
dynamic_sum(1, 2, 3, name='Tom', age=10)- 面向?qū)ο缶幊?(OOP)
- 核心:理解類(Class)與對(duì)象(Object)。掌握OOP三大特性:封裝(隱藏內(nèi)部細(xì)節(jié))、繼承(實(shí)現(xiàn)代碼復(fù)用)、多態(tài)(同一接口不同實(shí)現(xiàn))。
- 示例:
class Animal:
def __init__(self, name): # 構(gòu)造方法
self.name = name # 實(shí)例變量
def speak(self): # 方法
raise NotImplementedError("子類必須實(shí)現(xiàn)此方法")
class Dog(Animal): # 繼承
def speak(self): # 多態(tài):重寫父類方法
return f"{self.name} says: Woof!"
my_dog = Dog("Buddy")
print(my_dog.speak()) # 輸出: Buddy says: Woof!- 文件與數(shù)據(jù)持久化
- 核心:使用
open()函數(shù)讀寫文本和二進(jìn)制文件。用with語(yǔ)句管理資源可自動(dòng)關(guān)閉文件。處理JSON、CSV等格式數(shù)據(jù)是日常必備技能。 - 示例:
- 核心:使用
# 使用with安全地讀寫文件
with open('note.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!\n這是第二行。")
with open('note.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 處理JSON數(shù)據(jù)(常用于API和配置)
import json
data = {'name': '小明', 'hobbies': ['閱讀', '游泳']}
json_str = json.dumps(data, ensure_ascii=False) # 轉(zhuǎn)為JSON字符串
loaded_data = json.loads(json_str) # 解析JSON字符串?? 第三階段:高級(jí)精通
深入語(yǔ)言特性和生態(tài),解決復(fù)雜工程問題。
- 常用高級(jí)特性
- 裝飾器:在不修改原函數(shù)代碼的情況下,為函數(shù)添加額外功能(如日志、計(jì)時(shí)、權(quán)限檢查)。
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 執(zhí)行耗時(shí): {end-start:.2f}秒")
return result
return wrapper
@timer
def some_task():
time.sleep(1)
some_task()- 生成器:使用
yield關(guān)鍵字,用于惰性生成大量數(shù)據(jù),節(jié)省內(nèi)存。
def fibonacci(limit):
a, b = 0, 1
while a < limit:
yield a # 每次產(chǎn)生一個(gè)值,函數(shù)狀態(tài)會(huì)暫停保留
a, b = b, a + b
for num in fibonacci(10):
print(num) # 輸出: 0 1 1 2 3 5 8- 上下文管理器:除了文件操作,可以自定義
__enter__和__exit__方法來管理資源(如網(wǎng)絡(luò)連接、數(shù)據(jù)庫(kù)連接)。
主流應(yīng)用領(lǐng)域與庫(kù)
- Web開發(fā):使用 Flask(輕量靈活)或 Django(功能全面)框架。
- 數(shù)據(jù)分析與科學(xué)計(jì)算:NumPy(數(shù)組計(jì)算)、Pandas(數(shù)據(jù)分析)、Matplotlib(數(shù)據(jù)可視化)。
- 人工智能與機(jī)器學(xué)習(xí):Scikit-learn(傳統(tǒng)機(jī)器學(xué)習(xí))、TensorFlow/PyTorch(深度學(xué)習(xí))。
- 自動(dòng)化與腳本:使用
os、sys、subprocess等標(biāo)準(zhǔn)庫(kù)進(jìn)行文件管理、系統(tǒng)操作。
性能優(yōu)化與工程化
- 性能分析:使用
cProfile、timeit模塊分析代碼瓶頸。 - 調(diào)試與測(cè)試:使用
pdb進(jìn)行調(diào)試,用unittest或pytest框架編寫單元測(cè)試。 - 代碼規(guī)范:遵循 PEP 8 風(fēng)格指南,使用 Black、isort 等工具自動(dòng)化格式化。
- 性能分析:使用
?? 如何有效提升?
- 遵循路徑:建議按上述三個(gè)階段順序?qū)W習(xí),每個(gè)階段打好基礎(chǔ)再進(jìn)入下一個(gè)。
- 實(shí)踐至上:學(xué)習(xí)每個(gè)知識(shí)點(diǎn)后,立刻動(dòng)手編寫代碼??梢詮臅械睦?、小型腳本(如自動(dòng)化整理文件、爬取天氣數(shù)據(jù))開始。
- 閱讀優(yōu)秀代碼:在GitHub上閱讀熱門項(xiàng)目的源碼,學(xué)習(xí)代碼組織方式和最佳實(shí)踐。
- 參與項(xiàng)目:找一個(gè)小型但完整的項(xiàng)目進(jìn)行實(shí)踐,例如用Flask搭建一個(gè)博客,或用Pandas分析一份數(shù)據(jù)集。這是將知識(shí)融會(huì)貫通的最佳方式。
如果你想深入了解某個(gè)特定領(lǐng)域(比如Web框架的詳細(xì)對(duì)比,或者數(shù)據(jù)科學(xué)庫(kù)的具體入門方法),可以在網(wǎng)上搜索更具體的資料和學(xué)習(xí)建議。
我將通過遞進(jìn)的示例,系統(tǒng)講解Python的核心語(yǔ)法、數(shù)據(jù)類型和函數(shù),幫助你從基礎(chǔ)到進(jìn)階。
一、Python基礎(chǔ)語(yǔ)法
1.1 變量與賦值
# 變量命名規(guī)范 name = "Python" # 字符串 version = 3.9 # 整數(shù) rating = 9.5 # 浮點(diǎn)數(shù) is_awesome = True # 布爾值 # 多重賦值 x, y, z = 1, 2, 3 # 鏈?zhǔn)劫x值 a = b = c = 100 # 變量交換(Python特有) m, n = 10, 20 m, n = n, m # 交換后 m=20, n=10
1.2 注釋與代碼結(jié)構(gòu)
# 單行注釋
"""
多行注釋(實(shí)際是三引號(hào)字符串)
通常用于模塊、函數(shù)說明
"""
# 代碼塊通過縮進(jìn)定義
if True:
print("縮進(jìn)4個(gè)空格") # 屬于if代碼塊
print("同一代碼塊")
print("已退出代碼塊") # 不屬于if代碼塊二、Python核心數(shù)據(jù)類型
2.1 數(shù)字類型
# 整數(shù) int_num = 42 # 十進(jìn)制 binary_num = 0b1010 # 二進(jìn)制: 10 hex_num = 0xFF # 十六進(jìn)制: 255 # 浮點(diǎn)數(shù) float_num = 3.14159 scientific = 1.23e-4 # 0.000123 # 復(fù)數(shù) complex_num = 3 + 4j # 數(shù)值運(yùn)算 print(10 / 3) # 浮點(diǎn)除法: 3.333... print(10 // 3) # 整除: 3 print(10 % 3) # 取模: 1 print(2 ** 3) # 冪運(yùn)算: 8
2.2 序列類型對(duì)比與操作
下表展示了Python主要序列類型的關(guān)鍵特性:
| 類型 | 可變性 | 創(chuàng)建方式 | 特點(diǎn) | 使用場(chǎng)景 |
|---|---|---|---|---|
| 列表 | 可變 | [1, 2, 3] 或 list() | 有序,元素可重復(fù),可包含不同類型 | 存儲(chǔ)可變數(shù)據(jù)集,如待辦事項(xiàng) |
| 元組 | 不可變 | (1, 2, 3) 或 tuple() | 有序,創(chuàng)建后不能修改 | 固定數(shù)據(jù)集合,如坐標(biāo)、配置項(xiàng) |
| 字符串 | 不可變 | "hello" 或 str() | 字符序列,支持多種操作 | 文本處理,格式化輸出 |
| 范圍 | 不可變 | range(5) | 生成數(shù)字序列,內(nèi)存高效 | 循環(huán)計(jì)數(shù),序列生成 |
# 列表操作
fruits = ['apple', 'banana', 'orange']
fruits.append('grape') # 末尾添加
fruits.insert(1, 'pear') # 指定位置插入
fruits.remove('banana') # 刪除元素
popped = fruits.pop() # 移除并返回最后一個(gè)
print(fruits[0:2]) # 切片: ['apple', 'pear']
# 列表推導(dǎo)式(高效創(chuàng)建列表)
squares = [x**2 for x in range(10) if x % 2 == 0]
# 結(jié)果: [0, 4, 16, 36, 64]
# 元組
coordinates = (10.5, 20.3)
x, y = coordinates # 解包
single_tuple = (42,) # 單元素元組需要逗號(hào)
# 字符串操作
text = "Python Programming"
print(text.upper()) # 轉(zhuǎn)大寫
print(text.find("Pro")) # 查找位置: 7
print(text.split(" ")) # 分割: ['Python', 'Programming']
print("Hello, {}!".format(name)) # 格式化
print(f"Version: {version}") # f-string (Python 3.6+)2.3 字典與集合
# 字典(鍵值對(duì)集合)
student = {
"name": "Alice",
"age": 20,
"courses": ["Math", "Physics"]
}
student["grade"] = "A" # 添加鍵值對(duì)
print(student.get("age")) # 安全獲取: 20
print(student.get("score", "N/A")) # 默認(rèn)值: N/A
# 遍歷字典
for key, value in student.items():
print(f"{key}: {value}")
# 字典推導(dǎo)式
squared_dict = {x: x**2 for x in range(5)}
# 結(jié)果: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 集合(無序不重復(fù)元素)
set_a = {1, 2, 3, 3, 4} # 自動(dòng)去重: {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
print(set_a | set_b) # 并集: {1, 2, 3, 4, 5, 6}
print(set_a & set_b) # 交集: {3, 4}
print(set_a - set_b) # 差集: {1, 2}三、流程控制
3.1 條件語(yǔ)句
# if-elif-else結(jié)構(gòu)
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
# 三元表達(dá)式
status = "及格" if score >= 60 else "不及格"
# 多條件判斷
age = 25
is_student = True
if 18 <= age <= 30 and is_student:
discount = 0.5
elif age > 60 or not is_student:
discount = 0.2
else:
discount = 03.2 循環(huán)結(jié)構(gòu)
# for循環(huán)遍歷序列
colors = ["red", "green", "blue"]
for i, color in enumerate(colors): # enumerate獲取索引和值
print(f"顏色{i}: {color}")
# 遍歷字典
for key in student.keys():
print(key)
# while循環(huán)
count = 0
while count < 5:
print(f"計(jì)數(shù): {count}")
count += 1
if count == 3:
break # 跳出循環(huán)
# 循環(huán)控制
for i in range(10):
if i % 2 == 0:
continue # 跳過偶數(shù)
print(f"奇數(shù): {i}")
# 循環(huán)中的else子句(循環(huán)正常結(jié)束時(shí)執(zhí)行)
for i in range(3):
print(i)
else:
print("循環(huán)完成")四、函數(shù)詳解
4.1 函數(shù)定義與調(diào)用
def greet(name, greeting="Hello"):
"""
問候函數(shù)
參數(shù):
name: 姓名
greeting: 問候語(yǔ),默認(rèn)為'Hello'
返回:
問候字符串
"""
return f"{greeting}, {name}!"
# 函數(shù)調(diào)用
print(greet("Alice")) # 位置參數(shù)
print(greet(greeting="Hi", name="Bob")) # 關(guān)鍵字參數(shù)
# 返回多個(gè)值(實(shí)際返回元組)
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 4, 1, 5])
print(f"最小值: {low}, 最大值: {high}")4.2 參數(shù)類型詳解
def flexible_func(a, b=10, *args, **kwargs):
"""
演示各種參數(shù)類型
a: 位置參數(shù)(必須)
b: 默認(rèn)參數(shù)(可選)
*args: 可變位置參數(shù)(元組)
**kwargs: 可變關(guān)鍵字參數(shù)(字典)
"""
print(f"a: {a}, b: ")
print(f"args: {args}")
print(f"kwargs: {kwargs}")
# 調(diào)用示例
flexible_func(1) # a:1, b:10, args:(), kwargs:{}
flexible_func(1, 2, 3, 4, x=5, y=6) # a:1, b:2, args:(3,4), kwargs:{'x':5,'y':6}
# 參數(shù)解包
params = {'name': 'Charlie', 'age': 25}
def person_info(name, age):
return f"{name} is {age} years old"
print(person_info(**params)) # 字典解包4.3 高階函數(shù)與lambda
# lambda表達(dá)式(匿名函數(shù))
add = lambda x, y: x + y
print(add(5, 3)) # 8
# 常用于排序
students = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Charlie', 'score': 78}
]
# 按分?jǐn)?shù)排序
sorted_students = sorted(students, key=lambda s: s['score'], reverse=True)
# map函數(shù):對(duì)序列每個(gè)元素應(yīng)用函數(shù)
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9, 16]
# filter函數(shù):過濾序列
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2, 4]
# 函數(shù)作為返回值
def make_multiplier(n):
def multiplier(x):
return x * n
return multiplier
double = make_multiplier(2)
print(double(5)) # 104.4 作用域與閉包
# 全局變量與局部變量
global_var = "全局"
def scope_test():
local_var = "局部"
print(global_var) # 可訪問全局變量
print(local_var) # 可訪問局部變量
# 修改全局變量需要聲明
global global_var
global_var = "已修改"
scope_test()
# print(local_var) # 錯(cuò)誤!不能訪問函數(shù)內(nèi)的局部變量
# 閉包:函數(shù)記住其外部作用域
def counter():
count = 0
def increment():
nonlocal count # 聲明非局部變量
count += 1
return count
return increment
my_counter = counter()
print(my_counter()) # 1
print(my_counter()) # 2 - count被記住了五、綜合實(shí)例:學(xué)生成績(jī)管理系統(tǒng)
class StudentManager:
"""學(xué)生成績(jī)管理類"""
def __init__(self):
self.students = {}
def add_student(self, name, scores):
"""添加學(xué)生及其成績(jī)"""
self.students[name] = scores
def calculate_average(self, name):
"""計(jì)算學(xué)生平均分"""
if name not in self.students:
return None
scores = self.students[name]
return sum(scores) / len(scores) if scores else 0
def get_top_student(self):
"""獲取平均分最高的學(xué)生"""
if not self.students:
return None
# 使用lambda和max函數(shù)
return max(self.students.items(),
key=lambda item: self.calculate_average(item[0]))
def analyze_scores(self):
"""成績(jī)分析"""
all_scores = []
for scores in self.students.values():
all_scores.extend(scores)
if not all_scores:
return "暫無數(shù)據(jù)"
analysis = {
'total_students': len(self.students),
'total_scores': len(all_scores),
'average_all': sum(all_scores) / len(all_scores),
'max_score': max(all_scores),
'min_score': min(all_scores)
}
return analysis
# 使用示例
manager = StudentManager()
# 添加學(xué)生數(shù)據(jù)
manager.add_student("Alice", [85, 92, 78])
manager.add_student("Bob", [76, 88, 91])
manager.add_student("Charlie", [92, 95, 89])
# 分析數(shù)據(jù)
print(f"Alice的平均分: {manager.calculate_average('Alice'):.2f}")
top_student = manager.get_top_student()
print(f"最高分學(xué)生: {top_student[0]}, 平均分: {manager.calculate_average(top_student[0]):.2f}")
analysis = manager.analyze_scores()
print(f"總學(xué)生數(shù): {analysis['total_students']}")
print(f"所有科目平均分: {analysis['average_all']:.2f}")學(xué)習(xí)建議
- 練習(xí)順序:先掌握基礎(chǔ)語(yǔ)法和數(shù)據(jù)類型,再深入函數(shù)和高級(jí)特性
- 實(shí)踐方法:每個(gè)代碼示例都手動(dòng)輸入并修改,觀察不同變化
- 項(xiàng)目驅(qū)動(dòng):嘗試用所學(xué)知識(shí)解決實(shí)際問題,如數(shù)據(jù)分析小腳本、自動(dòng)化工具
- 調(diào)試技巧:使用
print()調(diào)試,逐步構(gòu)建復(fù)雜功能
這個(gè)知識(shí)體系覆蓋了Python核心概念的80%,掌握后即可編寫實(shí)用的Python程序。建議按照示例順序?qū)嵺`,逐步建立編程思維。
一、面向?qū)ο缶幊谈呒?jí)特性
1.1 類方法與靜態(tài)方法
class Date:
"""日期類演示類方法與靜態(tài)方法"""
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
# 實(shí)例方法 - 操作實(shí)例屬性
def display(self):
return f"{self.year}-{self.month:02d}-{self.day:02d}"
@classmethod # 類方法 - 操作類本身
def from_string(cls, date_string):
"""從字符串創(chuàng)建Date實(shí)例"""
year, month, day = map(int, date_string.split('-'))
return cls(year, month, day) # cls代表類本身
@classmethod
def is_leap_year(cls, year):
"""判斷是否為閏年"""
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
@staticmethod # 靜態(tài)方法 - 工具函數(shù),不依賴類或?qū)嵗?
def days_in_month(month, year):
"""返回指定月份的天數(shù)"""
if month in [1, 3, 5, 7, 8, 10, 12]:
return 31
elif month in [4, 6, 9, 11]:
return 30
elif month == 2:
return 29 if Date.is_leap_year(year) else 28
else:
raise ValueError("無效月份")
# 使用示例
d1 = Date(2024, 5, 20)
print(d1.display()) # 實(shí)例方法
d2 = Date.from_string("2024-05-21") # 類方法作為替代構(gòu)造器
print(d2.display())
print(Date.is_leap_year(2024)) # True
print(Date.days_in_month(2, 2024)) # 291.2 屬性裝飾器與描述符
class Temperature:
"""使用屬性裝飾器控制屬性訪問"""
def __init__(self, celsius=0):
self._celsius = celsius # 私有屬性
@property
def celsius(self):
"""獲取攝氏溫度"""
print("獲取攝氏溫度")
return self._celsius
@celsius.setter
def celsius(self, value):
"""設(shè)置攝氏溫度"""
if value < -273.15:
raise ValueError("溫度不能低于絕對(duì)零度(-273.15°C)")
print(f"設(shè)置攝氏溫度為: {value}")
self._celsius = value
@property
def fahrenheit(self):
"""計(jì)算華氏溫度(只讀屬性)"""
return self._celsius * 9/5 + 32
@fahrenheit.setter
def fahrenheit(self, value):
"""通過華氏溫度設(shè)置攝氏溫度"""
self._celsius = (value - 32) * 5/9
# 描述符類
class ValidatedAttribute:
"""自定義描述符驗(yàn)證屬性值"""
def __init__(self, min_value=None, max_value=None):
self.min_value = min_value
self.max_value = max_value
self.data = {}
def __get__(self, instance, owner):
if instance is None:
return self
return self.data.get(id(instance))
def __set__(self, instance, value):
if self.min_value is not None and value < self.min_value:
raise ValueError(f"值不能小于 {self.min_value}")
if self.max_value is not None and value > self.max_value:
raise ValueError(f"值不能大于 {self.max_value}")
self.data[id(instance)] = value
class Product:
price = ValidatedAttribute(min_value=0, max_value=10000)
quantity = ValidatedAttribute(min_value=0, max_value=1000)
def __init__(self, name, price, quantity):
self.name = name
self.price = price # 觸發(fā)描述符的__set__
self.quantity = quantity
# 使用示例
temp = Temperature(25)
print(f"攝氏: {temp.celsius}°C") # 觸發(fā)@property
print(f"華氏: {temp.fahrenheit}°F")
temp.celsius = 30 # 觸發(fā)@celsius.setter
temp.fahrenheit = 100 # 觸發(fā)@fahrenheit.setter
try:
p = Product("手機(jī)", -100, 10)
except ValueError as e:
print(f"錯(cuò)誤: {e}") # 值不能小于 0
p2 = Product("筆記本", 5000, 5)
print(f"{p2.name}: 價(jià)格{p2.price}, 庫(kù)存{p2.quantity}")二、裝飾器高級(jí)應(yīng)用
2.1 參數(shù)化裝飾器
import time
from functools import wraps
from typing import Callable, Any
def retry(max_attempts: int = 3, delay: float = 1.0):
"""
參數(shù)化重試裝飾器
Args:
max_attempts: 最大重試次數(shù)
delay: 重試間隔(秒)
"""
def decorator(func: Callable) -> Callable:
@wraps(func)
def wrapper(*args, **kwargs) -> Any:
last_exception = None
for attempt in range(max_attempts):
try:
print(f"嘗試第 {attempt + 1} 次...")
return func(*args, **kwargs)
except Exception as e:
last_exception = e
if attempt < max_attempts - 1:
print(f"失敗,{delay}秒后重試...")
time.sleep(delay)
print(f"所有 {max_attempts} 次嘗試均失敗")
raise last_exception
return wrapper
return decorator
# 創(chuàng)建緩存裝飾器
def cache(maxsize: int = 128):
"""帶LRU緩存的參數(shù)化裝飾器"""
def decorator(func: Callable) -> Callable:
cache_dict = {}
cache_keys = []
@wraps(func)
def wrapper(*args, **kwargs):
# 創(chuàng)建緩存鍵
key = (args, frozenset(kwargs.items()))
if key in cache_dict:
print(f"緩存命中: {func.__name__}{args}")
return cache_dict[key]
print(f"計(jì)算: {func.__name__}{args}")
result = func(*args, **kwargs)
# LRU緩存邏輯
cache_dict[key] = result
cache_keys.append(key)
if len(cache_dict) > maxsize:
oldest_key = cache_keys.pop(0)
del cache_dict[oldest_key]
return result
wrapper.clear_cache = lambda: (cache_dict.clear(), cache_keys.clear())
return wrapper
return decorator
# 使用參數(shù)化裝飾器
@retry(max_attempts=5, delay=0.5)
def unstable_api_call():
"""模擬不穩(wěn)定的API調(diào)用"""
import random
if random.random() < 0.7:
raise ConnectionError("API連接失敗")
return "API調(diào)用成功"
@cache(maxsize=2)
def expensive_computation(n):
"""模擬昂貴計(jì)算"""
print(f"執(zhí)行昂貴計(jì)算: {n}")
time.sleep(1)
return n * n
# 測(cè)試
try:
result = unstable_api_call()
print(result)
except Exception as e:
print(f"最終失敗: {e}")
print(expensive_computation(5)) # 計(jì)算
print(expensive_computation(5)) # 從緩存獲取
print(expensive_computation(3)) # 計(jì)算
print(expensive_computation(4)) # 計(jì)算,觸發(fā)LRU淘汰
print(expensive_computation(5)) # 重新計(jì)算(已被淘汰)2.2 類裝飾器
from dataclasses import dataclass, field
from typing import List, ClassVar
import json
# 類裝飾器:為類添加單例模式
def singleton(cls):
"""單例模式裝飾器"""
instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class AppConfig:
def __init__(self):
self.settings = {"theme": "dark", "language": "zh-CN"}
def update(self, key, value):
self.settings[key] = value
# 使用@dataclass自動(dòng)生成方法
@dataclass(order=True, frozen=False) # frozen=True創(chuàng)建不可變實(shí)例
class Person:
"""使用dataclass自動(dòng)生成__init__, __repr__, __eq__等方法"""
name: str
age: int
email: str = "" # 默認(rèn)值
hobbies: List[str] = field(default_factory=list) # 可變默認(rèn)值的正確寫法
id: ClassVar[int] = 0 # 類變量
def __post_init__(self):
"""初始化后自動(dòng)調(diào)用"""
Person.id += 1
def to_dict(self):
return {"name": self.name, "age": self.age, "hobbies": self.hobbies}
# 測(cè)試
config1 = AppConfig()
config2 = AppConfig()
print(f"是否是同一個(gè)實(shí)例: {config1 is config2}") # True
config1.update("theme", "light")
print(f"config2的主題: {config2.settings['theme']}") # light
# dataclass使用
p1 = Person("Alice", 25, "alice@example.com", ["reading", "swimming"])
p2 = Person("Bob", 30)
print(p1) # Person(name='Alice', age=25, email='alice@example.com', hobbies=['reading', 'swimming'])
print(p1 == p2) # False
print(p1.to_dict()) # {'name': 'Alice', 'age': 25, 'hobbies': ['reading', 'swimming']}三、上下文管理器與資源管理
3.1 自定義上下文管理器
import sqlite3
from contextlib import contextmanager
from typing import Optional, Iterator
# 方法1:使用類實(shí)現(xiàn)上下文管理器
class DatabaseConnection:
"""數(shù)據(jù)庫(kù)連接上下文管理器"""
def __init__(self, db_path: str):
self.db_path = db_path
self.connection: Optional[sqlite3.Connection] = None
def __enter__(self) -> sqlite3.Connection:
"""進(jìn)入上下文時(shí)調(diào)用"""
print(f"連接數(shù)據(jù)庫(kù): {self.db_path}")
self.connection = sqlite3.connect(self.db_path)
self.connection.row_factory = sqlite3.Row # 返回字典樣式的行
return self.connection
def __exit__(self, exc_type, exc_val, exc_tb):
"""退出上下文時(shí)調(diào)用"""
if self.connection:
if exc_type is None:
print("提交事務(wù)并關(guān)閉連接")
self.connection.commit()
else:
print(f"發(fā)生錯(cuò)誤: {exc_val},回滾事務(wù)")
self.connection.rollback()
self.connection.close()
print("數(shù)據(jù)庫(kù)連接已關(guān)閉")
return False # 不抑制異常,True表示抑制
# 方法2:使用@contextmanager裝飾器
@contextmanager
def temp_table(connection: sqlite3.Connection, table_name: str) -> Iterator:
"""創(chuàng)建臨時(shí)表的上下文管理器"""
cursor = connection.cursor()
try:
print(f"創(chuàng)建臨時(shí)表: {table_name}")
cursor.execute(f"CREATE TEMP TABLE {table_name} (id INTEGER, name TEXT)")
yield cursor # 這里將控制權(quán)交給with塊內(nèi)的代碼
finally:
print(f"清理臨時(shí)表: {table_name}")
cursor.execute(f"DROP TABLE IF EXISTS {table_name}")
cursor.close()
# 方法3:處理多個(gè)資源的上下文管理器
from contextlib import ExitStack
class MultiResourceManager:
"""管理多個(gè)資源的上下文管理器"""
def __init__(self):
self.stack = ExitStack()
def add_file(self, filepath, mode='r'):
"""添加文件到資源棧"""
file_obj = self.stack.enter_context(open(filepath, mode, encoding='utf-8'))
return file_obj
def add_connection(self, db_path):
"""添加數(shù)據(jù)庫(kù)連接到資源棧"""
conn = self.stack.enter_context(DatabaseConnection(db_path))
return conn
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stack.close()
# 使用示例
print("=== 示例1: 數(shù)據(jù)庫(kù)連接上下文 ===")
with DatabaseConnection(":memory:") as conn:
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
cursor.execute("INSERT INTO users (name) VALUES (?)", ("Alice",))
with temp_table(conn, "temp_data") as temp_cursor:
temp_cursor.execute("INSERT INTO temp_data VALUES (1, '測(cè)試')")
temp_cursor.execute("SELECT * FROM temp_data")
print(temp_cursor.fetchall())
print("\n=== 示例2: 多資源管理 ===")
with MultiResourceManager() as manager:
# 自動(dòng)管理多個(gè)資源
conn = manager.add_connection(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE test (id INTEGER)")
# 可以繼續(xù)添加其他資源
# file = manager.add_file('test.txt', 'w')
# file.write('test content')
print("\n=== 示例3: 使用contextlib實(shí)用工具 ===")
from contextlib import suppress, redirect_stdout
import io
# suppress忽略指定異常
with suppress(FileNotFoundError):
with open("不存在的文件.txt") as f:
content = f.read()
# redirect_stdout重定向輸出
output = io.StringIO()
with redirect_stdout(output):
print("這條信息不會(huì)顯示在控制臺(tái)")
print("而是被重定向到StringIO")
print(f"捕獲的輸出: {output.getvalue()}")四、元類與元編程
4.1 自定義元類
class SingletonMeta(type):
"""單例模式元類"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
print(f"創(chuàng)建 {cls.__name__} 的唯一實(shí)例")
cls._instances[cls] = super().__call__(*args, **kwargs)
else:
print(f"返回 {cls.__name__} 的現(xiàn)有實(shí)例")
return cls._instances[cls]
class ValidateAttributesMeta(type):
"""驗(yàn)證類屬性的元類"""
def __new__(mcs, name, bases, attrs):
print(f"\n創(chuàng)建類: {name}")
# 驗(yàn)證屬性名不能以下劃線開頭(示例規(guī)則)
invalid_attrs = []
for attr_name in attrs:
if attr_name.startswith('_') and not attr_name.startswith('__'):
invalid_attrs.append(attr_name)
if invalid_attrs:
print(f"警告: 屬性 {invalid_attrs} 不建議以下劃線開頭")
# 自動(dòng)添加類版本信息
if '__version__' not in attrs:
attrs['__version__'] = '1.0.0'
return super().__new__(mcs, name, bases, attrs)
# 使用元類
class Database(metaclass=SingletonMeta):
def __init__(self, name):
self.name = name
self.connected = False
def connect(self):
self.connected = True
print(f"{self.name} 數(shù)據(jù)庫(kù)已連接")
class UserModel(metaclass=ValidateAttributesMeta):
"""用戶模型類,屬性會(huì)被元類驗(yàn)證"""
_private_data = "不應(yīng)直接訪問" # 這會(huì)觸發(fā)警告
name = "默認(rèn)用戶"
email = ""
def get_info(self):
return f"{self.name} <{self.email}>"
# 測(cè)試
print("=== 元類示例1: 單例模式 ===")
db1 = Database("主數(shù)據(jù)庫(kù)")
db1.connect()
db2 = Database("主數(shù)據(jù)庫(kù)") # 返回同一個(gè)實(shí)例
print(f"db1 is db2: {db1 is db2}")
print(f"db2.name: {db2.name}")
print("\n=== 元類示例2: 屬性驗(yàn)證 ===")
user = UserModel()
print(f"UserModel版本: {UserModel.__version__}")
print(f"用戶信息: {user.get_info()}")
# 動(dòng)態(tài)創(chuàng)建類
print("\n=== 動(dòng)態(tài)創(chuàng)建類 ===")
def class_factory(class_name, base_classes, attributes):
"""動(dòng)態(tài)創(chuàng)建類的工廠函數(shù)"""
return type(class_name, base_classes, attributes)
# 動(dòng)態(tài)創(chuàng)建類
Animal = class_factory(
'Animal',
(),
{
'species': '未知',
'__init__': lambda self, name: setattr(self, 'name', name),
'speak': lambda self: print(f"{self.name} 發(fā)出聲音")
}
)
cat = Animal("貓咪")
cat.species = "貓科"
cat.speak()
print(f"物種: {cat.species}")五、并發(fā)與并行編程
5.1 多線程與線程安全
import threading
import time
import concurrent.futures
from queue import Queue, Empty
from typing import List
import random
# 線程安全的計(jì)數(shù)器
class ThreadSafeCounter:
def __init__(self):
self._value = 0
self._lock = threading.Lock()
def increment(self):
with self._lock: # 自動(dòng)獲取和釋放鎖
self._value += 1
return self._value
@property
def value(self):
with self._lock:
return self._value
# 生產(chǎn)者-消費(fèi)者模式
class ProducerConsumer:
def __init__(self, max_size=5):
self.queue = Queue(maxsize=max_size)
self.stop_event = threading.Event()
def producer(self, producer_id: int):
"""生產(chǎn)者線程函數(shù)"""
while not self.stop_event.is_set():
item = f"產(chǎn)品-{producer_id}-{time.time():.2f}"
try:
self.queue.put(item, timeout=1)
print(f"生產(chǎn)者{producer_id} 生產(chǎn): {item}")
time.sleep(random.uniform(0.1, 0.5))
except Exception as e:
break
def consumer(self, consumer_id: int):
"""消費(fèi)者線程函數(shù)"""
while not self.stop_event.is_set() or not self.queue.empty():
try:
item = self.queue.get(timeout=1)
print(f"消費(fèi)者{consumer_id} 消費(fèi): {item}")
self.queue.task_done()
time.sleep(random.uniform(0.2, 0.8))
except Empty:
continue
def run(self, num_producers=2, num_consumers=3, duration=5):
"""運(yùn)行生產(chǎn)消費(fèi)過程"""
threads = []
# 創(chuàng)建生產(chǎn)者線程
for i in range(num_producers):
t = threading.Thread(target=self.producer, args=(i,))
t.daemon = True
threads.append(t)
t.start()
# 創(chuàng)建消費(fèi)者線程
for i in range(num_consumers):
t = threading.Thread(target=self.consumer, args=(i,))
t.daemon = True
threads.append(t)
t.start()
# 運(yùn)行指定時(shí)間
time.sleep(duration)
self.stop_event.set()
# 等待隊(duì)列清空
self.queue.join()
print("所有任務(wù)完成")
# 使用ThreadPoolExecutor
def process_task(task_id: int) -> str:
"""模擬處理任務(wù)"""
sleep_time = random.uniform(0.5, 2.0)
print(f"任務(wù){(diào)task_id} 開始執(zhí)行,預(yù)計(jì)耗時(shí){sleep_time:.1f}秒")
time.sleep(sleep_time)
result = f"任務(wù){(diào)task_id} 完成"
return result
def execute_with_threadpool():
"""使用線程池執(zhí)行任務(wù)"""
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
# 提交任務(wù)
future_to_task = {
executor.submit(process_task, i): i
for i in range(10)
}
# 收集結(jié)果
results = []
for future in concurrent.futures.as_completed(future_to_task):
task_id = future_to_task[future]
try:
result = future.result()
results.append(result)
print(result)
except Exception as e:
print(f"任務(wù){(diào)task_id} 生成異常: {e}")
print(f"\n總共完成 {len(results)} 個(gè)任務(wù)")
# 測(cè)試
print("=== 線程安全計(jì)數(shù)器 ===")
counter = ThreadSafeCounter()
def worker(counter: ThreadSafeCounter, iterations: int):
for _ in range(iterations):
counter.increment()
threads = []
for _ in range(10):
t = threading.Thread(target=worker, args=(counter, 100))
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"最終計(jì)數(shù)值: {counter.value} (期望值: 1000)")
print("\n=== 生產(chǎn)者-消費(fèi)者模式 ===")
pc = ProducerConsumer(max_size=3)
pc.run(duration=3)
print("\n=== 線程池執(zhí)行器 ===")
execute_with_threadpool()5.2 異步編程(asyncio)
import asyncio
import aiohttp
import asyncpg
from datetime import datetime
# 異步上下文管理器
class AsyncDatabaseConnection:
"""異步數(shù)據(jù)庫(kù)連接"""
async def __aenter__(self):
print("異步連接數(shù)據(jù)庫(kù)...")
self.conn = await asyncpg.connect(
user='user', password='password',
database='test', host='localhost'
)
return self.conn
async def __aexit__(self, exc_type, exc_val, exc_tb):
print("異步關(guān)閉數(shù)據(jù)庫(kù)連接...")
await self.conn.close()
# 異步迭代器
class AsyncDataStreamer:
"""異步數(shù)據(jù)流"""
def __init__(self, limit=10, delay=0.5):
self.limit = limit
self.delay = delay
self.current = 0
def __aiter__(self):
return self
async def __anext__(self):
if self.current >= self.limit:
raise StopAsyncIteration
await asyncio.sleep(self.delay)
data = f"數(shù)據(jù)塊-{self.current}-{datetime.now().timestamp()}"
self.current += 1
return data
# 異步任務(wù)示例
async def fetch_url(session: aiohttp.ClientSession, url: str) -> str:
"""異步獲取URL內(nèi)容"""
try:
print(f"開始獲取: {url}")
async with session.get(url, timeout=10) as response:
content = await response.text()
return f"{url}: {len(content)} 字符"
except Exception as e:
return f"{url}: 錯(cuò)誤 - {str(e)}"
async def process_data_stream():
"""處理異步數(shù)據(jù)流"""
print("開始處理數(shù)據(jù)流...")
streamer = AsyncDataStreamer(limit=5, delay=0.3)
async for data in streamer:
print(f"接收到: {data}")
# 模擬數(shù)據(jù)處理
await asyncio.sleep(0.1)
print("數(shù)據(jù)流處理完成")
async def concurrent_url_fetcher():
"""并發(fā)獲取多個(gè)URL"""
urls = [
"https://httpbin.org/delay/1",
"https://httpbin.org/delay/2",
"https://httpbin.org/delay/1",
"https://jsonplaceholder.typicode.com/posts/1",
]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(*tasks, return_exceptions=True)
print("\n獲取結(jié)果:")
for result in results:
print(f" {result}")
async def main():
"""主異步函數(shù)"""
print("=== 異步編程示例 ===\n")
# 示例1: 異步數(shù)據(jù)流
await process_data_stream()
print("\n" + "="*50 + "\n")
# 示例2: 并發(fā)URL獲取
await concurrent_url_fetcher()
print("\n" + "="*50 + "\n")
# 示例3: 異步任務(wù)控制
print("異步任務(wù)控制示例:")
# 創(chuàng)建任務(wù)
task1 = asyncio.create_task(fetch_data("任務(wù)1", 2))
task2 = asyncio.create_task(fetch_data("任務(wù)2", 1))
# 等待特定任務(wù)完成
done, pending = await asyncio.wait([task1, task2], timeout=1.5)
print(f"已完成: {len(done)} 個(gè)任務(wù)")
print(f"仍在進(jìn)行: {len(pending)} 個(gè)任務(wù)")
# 取消剩余任務(wù)
for task in pending:
task.cancel()
try:
await asyncio.gather(*pending, return_exceptions=True)
except asyncio.CancelledError:
print("已取消剩余任務(wù)")
async def fetch_data(name: str, delay: float) -> str:
"""模擬異步數(shù)據(jù)獲取"""
await asyncio.sleep(delay)
return f"{name} 完成,延遲 {delay}秒"
# 運(yùn)行異步程序
if __name__ == "__main__":
# 對(duì)于異步程序,需要特殊方式運(yùn)行
print("注意: 異步代碼需要合適的運(yùn)行環(huán)境")
print("可以使用以下方式運(yùn)行:")
print("1. 在Jupyter中使用: await main()")
print("2. 在腳本中使用: asyncio.run(main())")
# 實(shí)際運(yùn)行代碼
# asyncio.run(main())六、性能優(yōu)化與元編程
6.1 使用__slots__減少內(nèi)存
import sys
from dataclasses import dataclass
from pympler import asizeof # 需要安裝: pip install pympler
class RegularUser:
"""普通類,使用__dict__存儲(chǔ)屬性"""
def __init__(self, user_id, name, email, age):
self.user_id = user_id
self.name = name
self.email = email
self.age = age
class SlotUser:
"""使用__slots__優(yōu)化內(nèi)存的類"""
__slots__ = ('user_id', 'name', 'email', 'age')
def __init__(self, user_id, name, email, age):
self.user_id = user_id
self.name = name
self.email = email
self.age = age
@dataclass
class DataClassUser:
"""使用dataclass"""
user_id: int
name: str
email: str
age: int
def memory_comparison():
"""比較不同類的內(nèi)存使用"""
# 創(chuàng)建大量實(shí)例
num_instances = 10000
# 普通類
regular_users = [RegularUser(i, f"User{i}", f"user{i}@example.com", 20+i%50)
for i in range(num_instances)]
# slots類
slot_users = [SlotUser(i, f"User{i}", f"user{i}@example.com", 20+i%50)
for i in range(num_instances)]
# dataclass
dataclass_users = [DataClassUser(i, f"User{i}", f"user{i}@example.com", 20+i%50)
for i in range(num_instances)]
# 計(jì)算內(nèi)存使用
reg_memory = sum(asizeof.asizeof(u) for u in regular_users[:100]) * (num_instances / 100)
slot_memory = sum(asizeof.asizeof(u) for u in slot_users[:100]) * (num_instances / 100)
dc_memory = sum(asizeof.asizeof(u) for u in dataclass_users[:100]) * (num_instances / 100)
print(f"內(nèi)存使用對(duì)比 ({num_instances}個(gè)實(shí)例):")
print(f"普通類: {reg_memory / 1024:.1f} KB")
print(f"Slots類: {slot_memory / 1024:.1f} KB")
print(f"Dataclass: {dc_memory / 1024:.1f} KB")
print(f"節(jié)省比例: {(1 - slot_memory/reg_memory)*100:.1f}%")
# 測(cè)試
if __name__ == "__main__":
print("=== 內(nèi)存優(yōu)化示例 ===")
# 單個(gè)實(shí)例對(duì)比
reg = RegularUser(1, "Alice", "alice@example.com", 25)
slot = SlotUser(1, "Alice", "alice@example.com", 25)
print(f"單個(gè)RegularUser大小: {sys.getsizeof(reg)} 字節(jié) + __dict__")
print(f"單個(gè)SlotUser大小: {sys.getsizeof(slot)} 字節(jié)")
# 嘗試動(dòng)態(tài)添加屬性
try:
reg.new_attr = "可以動(dòng)態(tài)添加" # 成功
print("普通類可以動(dòng)態(tài)添加屬性")
except:
print("普通類無法動(dòng)態(tài)添加屬性")
try:
slot.new_attr = "嘗試動(dòng)態(tài)添加" # 失敗
print("Slots類可以動(dòng)態(tài)添加屬性")
except AttributeError:
print("Slots類無法動(dòng)態(tài)添加屬性")
print("\n批量?jī)?nèi)存對(duì)比:")
memory_comparison()學(xué)習(xí)建議
- 循序漸進(jìn):先掌握一個(gè)主題再進(jìn)入下一個(gè),特別是異步編程需要扎實(shí)的基礎(chǔ)
- 動(dòng)手實(shí)踐:修改示例代碼,觀察不同參數(shù)和行為變化
- 理解原理:了解每個(gè)特性的適用場(chǎng)景和優(yōu)缺點(diǎn),不濫用高級(jí)特性
- 結(jié)合實(shí)際:在工作中找到應(yīng)用場(chǎng)景,解決實(shí)際問題
- 性能考量:只有在確實(shí)需要優(yōu)化時(shí)才使用__slots__等高級(jí)優(yōu)化技術(shù)
這些進(jìn)階知識(shí)點(diǎn)是成為Python高級(jí)開發(fā)者的關(guān)鍵,掌握它們能編寫更高效、更優(yōu)雅、更易維護(hù)的代碼。建議每個(gè)主題都創(chuàng)建自己的練習(xí)項(xiàng)目,加深理解。
到此這篇關(guān)于小學(xué)生必須掌握的Python語(yǔ)法與代碼示例的文章就介紹到這了,更多相關(guān)Python語(yǔ)法與代碼示例內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- python語(yǔ)法筆記之Python?raise語(yǔ)句用法詳解
- Python核心語(yǔ)法與常用庫(kù)完全學(xué)習(xí)指南
- Python中kwargs.get()方法語(yǔ)法及高級(jí)用法詳解
- Python基本語(yǔ)法總結(jié)大全(含java、js對(duì)比)
- Python Playwright 語(yǔ)法知識(shí)詳解(推薦)
- Python語(yǔ)法詳解及與Java的差異對(duì)比
- 邏輯回歸算法詳解與Python實(shí)現(xiàn)完整代碼示例
- Python中的循環(huán)語(yǔ)句詳細(xì)代碼示例
- Python實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接池的代碼示例和最佳實(shí)踐
相關(guān)文章
Python xlwings插入Excel圖片的實(shí)現(xiàn)方法
這篇文章主要介紹了Python xlwings插入Excel圖片的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
pytorch cnn 識(shí)別手寫的字實(shí)現(xiàn)自建圖片數(shù)據(jù)
這篇文章主要介紹了pytorch cnn 識(shí)別手寫的字實(shí)現(xiàn)自建圖片數(shù)據(jù),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-05-05
如何利用Python讓Excel快速按條件篩選數(shù)據(jù)
平時(shí)總是要對(duì)Excel進(jìn)行操作,整理了一下平時(shí)經(jīng)常會(huì)用到的操作,下面這篇文章主要給大家介紹了關(guān)于如何利用Python讓Excel快速按條件篩選數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12
Python實(shí)現(xiàn)結(jié)構(gòu)化日志系統(tǒng)的完整方案和最佳實(shí)踐
在現(xiàn)代軟件系統(tǒng)中,日志不僅是調(diào)試和問題排查的工具,更是系統(tǒng)可觀測(cè)性的核心組成部分,本文將深入探討結(jié)構(gòu)化日志系統(tǒng)的設(shè)計(jì)原理、實(shí)現(xiàn)方法和最佳實(shí)踐,提供完整的Python實(shí)現(xiàn)方案,希望對(duì)大家有所幫助2025-12-12
詳解python os.path.exists判斷文件或文件夾是否存在
這篇文章主要介紹了詳解python os.path.exists判斷文件或文件夾是否存在,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
python實(shí)現(xiàn)多線程的方式及多條命令并發(fā)執(zhí)行
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)多線程的方式及多條命令并發(fā)執(zhí)行,感興趣的小伙伴們可以參考一下2016-06-06
python神經(jīng)網(wǎng)絡(luò)VGG16模型復(fù)現(xiàn)及其如何預(yù)測(cè)詳解
這篇文章主要為大家介紹了VGG16模型的復(fù)現(xiàn)及其詳解(包含如何預(yù)測(cè)),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

