【Python面試題】Python面試之基礎知識常見面試題3-匯總篇(精選30個)

目錄

  • 專欄導讀
    • 前言
    • 1. 字典的內存管理機制是什么?
    • 2. 列表的內存管理機制是什么?
    • 3. 元組和列表的區別
    • 4. 字符串插值的方法
    • 5. 閉包、裝飾器的原理
      • 閉包(Closure)
      • 裝飾器(Decorator)
    • 6. map、filter的區別
    • 7. range()函數的用法
    • 8. __new__方法和__init__方法
    • 9. 比較:is vs ==
    • 10. any和all
    • 11. with語句(上下文管理器)
    • 12. 迭代器、生成器的區別
      • 迭代器(Iterator)
      • 生成器(Generator)
    • 13. 打亂一個列表的元素
    • 14. 將元組變為字典
    • 15. JSON序列化
    • 16. Python中的傳參形式
    • 17. 如何修改全局變量
    • 18. Python中的遞歸
    • 19. 深拷貝和淺拷貝
    • 20. *args和**kwargs的含義
    • 21. 什么是單例模式
    • 22. 什么是多態
    • 23. 解釋一下模塊和包
      • 模塊(Module)
      • 包(Package)
    • 24. 什么是asyncio?它有什么用途?
    • 25. 什么是協程?
    • 26. 協程和線程的區別
    • 27. Future和Task的區別
    • 28. Python中的元類(Metaclass)
    • 29. Python中的描述符(Descriptor)
    • 30. Python中的上下文變量(Context Variables)
    • 總結
      • 重點掌握的概念:
      • 面試建議:
  • 結尾

專欄導讀

  • 🌸 歡迎來到Python辦公自動化專欄—Python處理辦公問題,解放您的雙手

  • 🏳??🌈 博客主頁:請點擊——> 一晌小貪歡的博客主頁求關注

  • 👍 該系列文章專欄:請點擊——>Python辦公自動化專欄求訂閱

  • 🕷 此外還有爬蟲專欄:請點擊——>Python爬蟲基礎專欄求訂閱

  • 📕 此外還有python基礎專欄:請點擊——>Python基礎學習專欄求訂閱

  • 文章作者技術和水平有限,如果文中出現錯誤,希望大家能指正🙏

  • ?? 歡迎各位佬關注! ??

前言

本文匯總了Python面試中最常見的基礎知識問題,涵蓋了數據結構、內存管理、面向對象、異步編程等多個方面。這些問題在Python面試中出現頻率極高,掌握這些知識點對于通過面試至關重要。

1. 字典的內存管理機制是什么?

核心概念:

  • Python字典使用哈希表(Hash Table)實現
  • 采用開放尋址法解決哈希沖突
  • 動態擴容機制
import sys# 字典的內存分配示例
my_dict = {}
for i in range(10):my_dict[i] = i * 2print(f"元素數量: {len(my_dict)}, 內存大小: {sys.getsizeof(my_dict)}")

關鍵特點:

  • 負載因子控制在2/3左右時觸發擴容
  • Python 3.7+保證插入順序
  • 鍵必須是不可變對象

2. 列表的內存管理機制是什么?

核心概念:

  • 基于動態數組實現
  • 預分配額外空間以減少頻繁擴容
  • 擴容策略:通常按1.5倍或2倍增長
import sys# 列表擴容機制演示
my_list = []
for i in range(20):my_list.append(i)print(f"長度: {len(my_list)}, 容量估算: {sys.getsizeof(my_list)}")

內存特點:

  • 連續內存存儲,支持隨機訪問
  • 末尾操作O(1),中間操作O(n)
  • 刪除元素時不會立即縮容

3. 元組和列表的區別

特性列表(List)元組(Tuple)
可變性可變不可變
語法[1, 2, 3](1, 2, 3)
性能較慢較快
內存占用較大較小
用途動態數據固定數據
# 性能對比
import timeitlist_time = timeit.timeit('x = [1, 2, 3, 4, 5]', number=1000000)
tuple_time = timeit.timeit('x = (1, 2, 3, 4, 5)', number=1000000)print(f"列表創建時間: {list_time}")
print(f"元組創建時間: {tuple_time}")

4. 字符串插值的方法

name = "Alice"
age = 25
score = 95.5# 方法1:% 格式化(舊式)
result1 = "姓名: %s, 年齡: %d, 分數: %.1f" % (name, age, score)# 方法2:str.format()方法
result2 = "姓名: {}, 年齡: {}, 分數: {:.1f}".format(name, age, score)
result3 = "姓名: {name}, 年齡: {age}, 分數: {score:.1f}".format(name=name, age=age, score=score)# 方法3:f-string(推薦,Python 3.6+)
result4 = f"姓名: {name}, 年齡: {age}, 分數: {score:.1f}"# 方法4:Template字符串
from string import Template
template = Template("姓名: $name, 年齡: $age")
result5 = template.substitute(name=name, age=age)

5. 閉包、裝飾器的原理

閉包(Closure)

def outer_function(x):def inner_function(y):return x + y  # 訪問外部函數的變量return inner_function# 創建閉包
add_10 = outer_function(10)
print(add_10(5))  # 輸出: 15# 檢查閉包
print(add_10.__closure__)  # 顯示閉包變量

裝飾器(Decorator)

import functools
import time# 簡單裝飾器
def timer(func):@functools.wraps(func)def wrapper(*args, **kwargs):start = time.time()result = func(*args, **kwargs)end = time.time()print(f"{func.__name__} 執行時間: {end - start:.4f}秒")return resultreturn wrapper# 帶參數的裝飾器
def repeat(times):def decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):for _ in range(times):result = func(*args, **kwargs)return resultreturn wrapperreturn decorator@timer
@repeat(3)
def greet(name):print(f"Hello, {name}!")

6. map、filter的區別

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# map: 對每個元素應用函數,返回新的迭代器
squares = list(map(lambda x: x**2, numbers))
print(f"平方: {squares}")  # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]# filter: 過濾滿足條件的元素
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"偶數: {even_numbers}")  # [2, 4, 6, 8, 10]# 等價的列表推導式
squares_comp = [x**2 for x in numbers]
even_comp = [x for x in numbers if x % 2 == 0]# 性能對比
import timeit
map_time = timeit.timeit(lambda: list(map(lambda x: x**2, range(1000))), number=1000)
comp_time = timeit.timeit(lambda: [x**2 for x in range(1000)], number=1000)

7. range()函數的用法

# 基本用法
print(list(range(5)))        # [0, 1, 2, 3, 4]
print(list(range(2, 8)))     # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 2))) # [0, 2, 4, 6, 8]
print(list(range(10, 0, -1))) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]# range對象特性
r = range(1000000)
print(type(r))           # <class 'range'>
print(sys.getsizeof(r))  # 內存占用很小,惰性求值
print(500000 in r)       # O(1) 時間復雜度的成員檢測# 實際應用
for i in range(3):print(f"第 {i+1} 次循環")# 與enumerate結合
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):print(f"{index}: {fruit}")

8. __new__方法和__init__方法

class Person:def __new__(cls, name, age):print(f"__new__ 被調用,創建實例")instance = super().__new__(cls)return instancedef __init__(self, name, age):print(f"__init__ 被調用,初始化實例")self.name = nameself.age = age# 單例模式示例
class Singleton:_instance = Nonedef __new__(cls):if cls._instance is None:cls._instance = super().__new__(cls)return cls._instancedef __init__(self):if not hasattr(self, 'initialized'):self.initialized = Trueprint("Singleton 初始化")# 測試
person = Person("Alice", 25)
s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # True

關鍵區別:

  • __new__:負責創建實例,返回實例對象
  • __init__:負責初始化實例,無返回值
  • __new__先于__init__執行

9. 比較:is vs ==

# == 比較值是否相等
# is 比較身份(內存地址)是否相同a = [1, 2, 3]
b = [1, 2, 3]
c = aprint(a == b)  # True,值相等
print(a is b)  # False,不是同一個對象
print(a is c)  # True,是同一個對象# 小整數緩存
x = 256
y = 256
print(x is y)  # True,小整數被緩存m = 257
n = 257
print(m is n)  # False(在某些情況下可能是True)# 字符串駐留
str1 = "hello"
str2 = "hello"
print(str1 is str2)  # True,字符串駐留# None的比較
value = None
print(value is None)     # 推薦
print(value == None)     # 不推薦

10. any和all

# any(): 任意一個為True則返回True
print(any([True, False, False]))   # True
print(any([False, False, False]))  # False
print(any([]))                     # False(空序列)# all(): 所有元素為True才返回True
print(all([True, True, True]))     # True
print(all([True, False, True]))    # False
print(all([]))                     # True(空序列)# 實際應用
numbers = [2, 4, 6, 8, 10]# 檢查是否所有數字都是偶數
all_even = all(num % 2 == 0 for num in numbers)
print(f"所有數字都是偶數: {all_even}")# 檢查是否有負數
has_negative = any(num < 0 for num in numbers)
print(f"包含負數: {has_negative}")# 驗證用戶輸入
def validate_user_data(data):required_fields = ['name', 'email', 'age']return all(field in data and data[field] for field in required_fields)user_data = {'name': 'Alice', 'email': 'alice@example.com', 'age': 25}
print(validate_user_data(user_data))  # True

11. with語句(上下文管理器)

# 文件操作
with open('example.txt', 'w') as f:f.write('Hello, World!')
# 文件自動關閉,即使發生異常# 自定義上下文管理器
class Timer:def __enter__(self):self.start = time.time()print("計時開始")return selfdef __exit__(self, exc_type, exc_val, exc_tb):self.end = time.time()print(f"計時結束,耗時: {self.end - self.start:.4f}秒")return False  # 不抑制異常with Timer():time.sleep(1)print("執行一些操作")# 使用contextlib
from contextlib import contextmanager@contextmanager
def database_transaction():print("開始事務")try:yield "數據庫連接"except Exception as e:print(f"回滾事務: {e}")raiseelse:print("提交事務")finally:print("關閉連接")with database_transaction() as db:print(f"使用 {db} 執行操作")

12. 迭代器、生成器的區別

迭代器(Iterator)

class NumberIterator:def __init__(self, max_num):self.max_num = max_numself.current = 0def __iter__(self):return selfdef __next__(self):if self.current < self.max_num:self.current += 1return self.currentraise StopIteration# 使用迭代器
for num in NumberIterator(5):print(num)  # 1, 2, 3, 4, 5

生成器(Generator)

# 生成器函數
def number_generator(max_num):current = 0while current < max_num:current += 1yield current# 生成器表達式
squares_gen = (x**2 for x in range(10))# 內存效率對比
import syslist_comp = [x**2 for x in range(1000)]
gen_exp = (x**2 for x in range(1000))print(f"列表推導式內存: {sys.getsizeof(list_comp)} bytes")
print(f"生成器表達式內存: {sys.getsizeof(gen_exp)} bytes")# 斐波那契數列生成器
def fibonacci():a, b = 0, 1while True:yield aa, b = b, a + bfib = fibonacci()
for _ in range(10):print(next(fib), end=' ')  # 0 1 1 2 3 5 8 13 21 34

主要區別:

  • 迭代器:實現__iter____next__方法的對象
  • 生成器:使用yield關鍵字的函數,自動實現迭代器協議
  • 生成器更簡潔,內存效率更高

13. 打亂一個列表的元素

import random# 方法1:random.shuffle()(原地打亂)
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(original_list)
print(f"打亂后: {original_list}")# 方法2:random.sample()(返回新列表)
original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffled_list = random.sample(original_list, len(original_list))
print(f"原列表: {original_list}")
print(f"新列表: {shuffled_list}")# 方法3:手動實現Fisher-Yates算法
def manual_shuffle(lst):result = lst.copy()for i in range(len(result) - 1, 0, -1):j = random.randint(0, i)result[i], result[j] = result[j], result[i]return resultoriginal_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffled = manual_shuffle(original_list)
print(f"手動打亂: {shuffled}")# 方法4:使用numpy(如果可用)
try:import numpy as nparr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])np.random.shuffle(arr)print(f"numpy打亂: {arr.tolist()}")
except ImportError:print("numpy未安裝")

14. 將元組變為字典

# 方法1:元組列表轉字典
tuples_list = [('a', 1), ('b', 2), ('c', 3)]
dict1 = dict(tuples_list)
print(dict1)  # {'a': 1, 'b': 2, 'c': 3}# 方法2:兩個元組轉字典
keys = ('name', 'age', 'city')
values = ('Alice', 25, 'Beijing')
dict2 = dict(zip(keys, values))
print(dict2)  # {'name': 'Alice', 'age': 25, 'city': 'Beijing'}# 方法3:嵌套元組轉字典
nested_tuple = (('x', 10), ('y', 20), ('z', 30))
dict3 = {k: v for k, v in nested_tuple}
print(dict3)  # {'x': 10, 'y': 20, 'z': 30}# 方法4:單個元組轉字典(索引作為鍵)
single_tuple = ('apple', 'banana', 'cherry')
dict4 = {i: v for i, v in enumerate(single_tuple)}
print(dict4)  # {0: 'apple', 1: 'banana', 2: 'cherry'}# 方法5:復雜轉換
data_tuple = (('user1', 'Alice', 25), ('user2', 'Bob', 30))
dict5 = {item[0]: {'name': item[1], 'age': item[2]} for item in data_tuple}
print(dict5)  # {'user1': {'name': 'Alice', 'age': 25}, 'user2': {'name': 'Bob', 'age': 30}}

15. JSON序列化

import json
from datetime import datetime
import decimal# 基本序列化和反序列化
data = {'name': 'Alice','age': 25,'hobbies': ['reading', 'swimming'],'is_student': False
}# 序列化為JSON字符串
json_string = json.dumps(data, ensure_ascii=False, indent=2)
print(json_string)# 反序列化
parsed_data = json.loads(json_string)
print(parsed_data)# 文件操作
with open('data.json', 'w', encoding='utf-8') as f:json.dump(data, f, ensure_ascii=False, indent=2)with open('data.json', 'r', encoding='utf-8') as f:loaded_data = json.load(f)# 自定義序列化
class DateTimeEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, datetime):return obj.isoformat()elif isinstance(obj, decimal.Decimal):return float(obj)return super().default(obj)complex_data = {'timestamp': datetime.now(),'price': decimal.Decimal('99.99')
}json_with_custom = json.dumps(complex_data, cls=DateTimeEncoder)
print(json_with_custom)# 處理不可序列化的對象
class Person:def __init__(self, name, age):self.name = nameself.age = agedef to_dict(self):return {'name': self.name, 'age': self.age}person = Person('Bob', 30)
person_json = json.dumps(person.to_dict())
print(person_json)

16. Python中的傳參形式

# 位置參數
def greet(name, age):print(f"Hello, {name}! You are {age} years old.")greet("Alice", 25)# 關鍵字參數
greet(age=30, name="Bob")# 默認參數
def greet_with_default(name, age=18, city="Unknown"):print(f"{name}, {age} years old, from {city}")greet_with_default("Charlie")
greet_with_default("David", city="Shanghai")# 可變位置參數 *args
def sum_all(*args):return sum(args)print(sum_all(1, 2, 3, 4, 5))  # 15# 可變關鍵字參數 **kwargs
def print_info(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")print_info(name="Eve", age=28, city="Beijing")# 混合使用
def complex_function(required, default="default", *args, **kwargs):print(f"Required: {required}")print(f"Default: {default}")print(f"Args: {args}")print(f"Kwargs: {kwargs}")complex_function("必需參數", "自定義默認值", 1, 2, 3, name="Alice", age=25)# 強制關鍵字參數(Python 3+)
def force_keyword(a, b, *, c, d):return a + b + c + d# force_keyword(1, 2, 3, 4)  # 錯誤
result = force_keyword(1, 2, c=3, d=4)  # 正確# 僅位置參數(Python 3.8+)
def position_only(a, b, /, c, d):return a + b + c + dresult = position_only(1, 2, c=3, d=4)  # 正確
# result = position_only(a=1, b=2, c=3, d=4)  # 錯誤

17. 如何修改全局變量

# 全局變量
global_var = 10
global_list = [1, 2, 3]def modify_global():global global_var  # 聲明要修改全局變量global_var = 20print(f"函數內 global_var: {global_var}")def modify_global_list():# 可變對象可以直接修改內容global_list.append(4)print(f"函數內 global_list: {global_list}")def reassign_global_list():global global_list  # 重新賦值需要global聲明global_list = [10, 20, 30]print(f"重新賦值后 global_list: {global_list}")print(f"修改前 global_var: {global_var}")
modify_global()
print(f"修改后 global_var: {global_var}")print(f"修改前 global_list: {global_list}")
modify_global_list()
print(f"修改后 global_list: {global_list}")reassign_global_list()
print(f"最終 global_list: {global_list}")# 嵌套函數中的nonlocal
def outer_function():outer_var = 100def inner_function():nonlocal outer_var  # 聲明要修改外層函數的變量outer_var = 200print(f"內層函數中 outer_var: {outer_var}")print(f"修改前 outer_var: {outer_var}")inner_function()print(f"修改后 outer_var: {outer_var}")outer_function()# 使用globals()和locals()
def show_scopes():local_var = "local"print(f"Local variables: {locals()}")print(f"Global variables: {list(globals().keys())[-5:]}")show_scopes()

18. Python中的遞歸

# 經典遞歸:階乘
def factorial(n):if n <= 1:return 1return n * factorial(n - 1)print(f"5! = {factorial(5)}")  # 120# 斐波那契數列(低效遞歸)
def fibonacci_recursive(n):if n <= 1:return nreturn fibonacci_recursive(n-1) + fibonacci_recursive(n-2)# 優化:記憶化遞歸
def fibonacci_memo(n, memo={}):if n in memo:return memo[n]if n <= 1:return nmemo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)return memo[n]# 使用functools.lru_cache裝飾器
from functools import lru_cache@lru_cache(maxsize=None)
def fibonacci_cached(n):if n <= 1:return nreturn fibonacci_cached(n-1) + fibonacci_cached(n-2)# 遞歸遍歷目錄
import osdef list_files_recursive(directory, level=0):items = []try:for item in os.listdir(directory):item_path = os.path.join(directory, item)indent = "  " * levelif os.path.isdir(item_path):items.append(f"{indent}{item}/")items.extend(list_files_recursive(item_path, level + 1))else:items.append(f"{indent}{item}")except PermissionError:items.append(f"{indent}[Permission Denied]")return items# 遞歸深度限制
import sys
print(f"默認遞歸深度限制: {sys.getrecursionlimit()}")# 尾遞歸優化(Python不支持,但可以手動轉換為迭代)
def factorial_iterative(n):result = 1for i in range(1, n + 1):result *= ireturn result

19. 深拷貝和淺拷貝

import copy# 原始數據
original = {'name': 'Alice','scores': [85, 90, 78],'info': {'age': 25,'city': 'Beijing'}
}# 淺拷貝
shallow_copy = copy.copy(original)
# 或者
shallow_copy2 = original.copy()
shallow_copy3 = dict(original)# 深拷貝
deep_copy = copy.deepcopy(original)# 修改測試
print("=== 修改前 ===")
print(f"Original: {original}")
print(f"Shallow: {shallow_copy}")
print(f"Deep: {deep_copy}")# 修改嵌套對象
original['scores'].append(95)
original['info']['age'] = 26print("\n=== 修改后 ===")
print(f"Original: {original}")
print(f"Shallow: {shallow_copy}")  # 嵌套對象被影響
print(f"Deep: {deep_copy}")        # 嵌套對象不受影響# 列表的拷貝
original_list = [[1, 2, 3], [4, 5, 6]]# 淺拷貝方法
shallow1 = original_list.copy()
shallow2 = original_list[:]
shallow3 = list(original_list)# 深拷貝
deep_list = copy.deepcopy(original_list)# 修改測試
original_list[0].append(4)
print(f"\nOriginal list: {original_list}")
print(f"Shallow copy: {shallow1}")  # 受影響
print(f"Deep copy: {deep_list}")    # 不受影響# 自定義拷貝行為
class CustomClass:def __init__(self, value):self.value = valueself.data = [1, 2, 3]def __copy__(self):print("執行淺拷貝")new_obj = CustomClass(self.value)new_obj.data = self.data  # 共享引用return new_objdef __deepcopy__(self, memo):print("執行深拷貝")new_obj = CustomClass(self.value)new_obj.data = copy.deepcopy(self.data, memo)return new_objoriginal_obj = CustomClass("test")
shallow_obj = copy.copy(original_obj)
deep_obj = copy.deepcopy(original_obj)

20. *args和**kwargs的含義

# *args:可變位置參數
def function_with_args(required_arg, *args):print(f"Required argument: {required_arg}")print(f"Additional arguments: {args}")print(f"Type of args: {type(args)}")for i, arg in enumerate(args):print(f"  args[{i}]: {arg}")function_with_args("必需參數", "額外1", "額外2", "額外3")# **kwargs:可變關鍵字參數
def function_with_kwargs(required_arg, **kwargs):print(f"Required argument: {required_arg}")print(f"Keyword arguments: {kwargs}")print(f"Type of kwargs: {type(kwargs)}")for key, value in kwargs.items():print(f"  {key}: {value}")function_with_kwargs("必需參數", name="Alice", age=25, city="Beijing")# 同時使用*args和**kwargs
def flexible_function(*args, **kwargs):print(f"Positional arguments: {args}")print(f"Keyword arguments: {kwargs}")flexible_function(1, 2, 3, name="Bob", age=30)# 參數順序:位置參數 -> *args -> 關鍵字參數 -> **kwargs
def complete_function(pos1, pos2, *args, kw1="default", **kwargs):print(f"pos1: {pos1}, pos2: {pos2}")print(f"args: {args}")print(f"kw1: {kw1}")print(f"kwargs: {kwargs}")complete_function("a", "b", "c", "d", kw1="custom", extra="value")# 解包參數
def add_three_numbers(a, b, c):return a + b + cnumbers = [1, 2, 3]
result = add_three_numbers(*numbers)  # 解包列表
print(f"Sum: {result}")data = {'a': 10, 'b': 20, 'c': 30}
result = add_three_numbers(**data)  # 解包字典
print(f"Sum: {result}")# 實際應用:裝飾器
def log_function_call(func):def wrapper(*args, **kwargs):print(f"調用函數 {func.__name__}")print(f"位置參數: {args}")print(f"關鍵字參數: {kwargs}")result = func(*args, **kwargs)print(f"返回值: {result}")return resultreturn wrapper@log_function_call
def calculate(x, y, operation="add"):if operation == "add":return x + yelif operation == "multiply":return x * yreturn 0calculate(5, 3, operation="multiply")

21. 什么是單例模式

# 方法1:使用__new__方法
class Singleton:_instance = None_initialized = Falsedef __new__(cls):if cls._instance is None:cls._instance = super().__new__(cls)return cls._instancedef __init__(self):if not self._initialized:self.value = 0self._initialized = True# 方法2:使用裝飾器
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 DatabaseConnection:def __init__(self):self.connection = "Connected to database"print("創建數據庫連接")# 方法3:使用元類
class SingletonMeta(type):_instances = {}def __call__(cls, *args, **kwargs):if cls not in cls._instances:cls._instances[cls] = super().__call__(*args, **kwargs)return cls._instances[cls]class Logger(metaclass=SingletonMeta):def __init__(self):self.logs = []print("創建日志記錄器")def log(self, message):self.logs.append(message)print(f"Log: {message}")# 方法4:模塊級單例(推薦)
# config.py
class Config:def __init__(self):self.debug = Trueself.database_url = "sqlite:///app.db"# 創建單例實例
config = Config()# 測試單例模式
print("=== 測試Singleton類 ===")
s1 = Singleton()
s2 = Singleton()
print(f"s1 is s2: {s1 is s2}")  # Trueprint("\n=== 測試DatabaseConnection ===")
db1 = DatabaseConnection()
db2 = DatabaseConnection()
print(f"db1 is db2: {db1 is db2}")  # Trueprint("\n=== 測試Logger ===")
logger1 = Logger()
logger2 = Logger()
print(f"logger1 is logger2: {logger1 is logger2}")  # True
logger1.log("第一條消息")
logger2.log("第二條消息")
print(f"logger1.logs: {logger1.logs}")
print(f"logger2.logs: {logger2.logs}")# 線程安全的單例
import threadingclass ThreadSafeSingleton:_instance = None_lock = threading.Lock()def __new__(cls):if cls._instance is None:with cls._lock:if cls._instance is None:cls._instance = super().__new__(cls)return cls._instance

22. 什么是多態

# 多態的基本概念:同一接口,不同實現
from abc import ABC, abstractmethod# 抽象基類
class Animal(ABC):@abstractmethoddef make_sound(self):pass@abstractmethoddef move(self):pass# 具體實現類
class Dog(Animal):def make_sound(self):return "汪汪"def move(self):return "跑步"class Cat(Animal):def make_sound(self):return "喵喵"def move(self):return "悄悄走"class Bird(Animal):def make_sound(self):return "嘰嘰喳喳"def move(self):return "飛翔"# 多態的使用
def animal_behavior(animal: Animal):print(f"動物發出聲音: {animal.make_sound()}")print(f"動物移動方式: {animal.move()}")# 創建不同的動物實例
animals = [Dog(), Cat(), Bird()]# 多態調用
for animal in animals:animal_behavior(animal)print("-" * 20)# 鴨子類型(Duck Typing)
class Duck:def make_sound(self):return "嘎嘎"def move(self):return "游泳"class Robot:def make_sound(self):return "嗶嗶"def move(self):return "機械移動"# 即使沒有繼承Animal,只要有相同的方法,就可以使用
duck = Duck()
robot = Robot()animal_behavior(duck)   # 正常工作
animal_behavior(robot)  # 也能正常工作# 運算符重載實現多態
class Vector:def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other):if isinstance(other, Vector):return Vector(self.x + other.x, self.y + other.y)elif isinstance(other, (int, float)):return Vector(self.x + other, self.y + other)else:raise TypeError(f"不支持的類型: {type(other)}")def __str__(self):return f"Vector({self.x}, {self.y})"# 多態的運算符重載
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2        # Vector + Vector
v4 = v1 + 5         # Vector + intprint(f"v1 + v2 = {v3}")
print(f"v1 + 5 = {v4}")# 策略模式體現多態
class PaymentStrategy(ABC):@abstractmethoddef pay(self, amount):passclass CreditCardPayment(PaymentStrategy):def pay(self, amount):return f"使用信用卡支付 {amount} 元"class AlipayPayment(PaymentStrategy):def pay(self, amount):return f"使用支付寶支付 {amount} 元"class WechatPayment(PaymentStrategy):def pay(self, amount):return f"使用微信支付 {amount} 元"class PaymentProcessor:def __init__(self, strategy: PaymentStrategy):self.strategy = strategydef process_payment(self, amount):return self.strategy.pay(amount)# 使用不同的支付策略
payments = [PaymentProcessor(CreditCardPayment()),PaymentProcessor(AlipayPayment()),PaymentProcessor(WechatPayment())
]for payment in payments:print(payment.process_payment(100))

23. 解釋一下模塊和包

模塊(Module)

# math_utils.py - 自定義模塊
def add(a, b):"""加法函數"""return a + bdef multiply(a, b):"""乘法函數"""return a * bPI = 3.14159class Calculator:def __init__(self):self.history = []def calculate(self, operation, a, b):if operation == 'add':result = add(a, b)elif operation == 'multiply':result = multiply(a, b)else:result = Noneself.history.append((operation, a, b, result))return result# 模塊的使用
# 方法1:導入整個模塊
import math_utils
result = math_utils.add(5, 3)
print(f"5 + 3 = {result}")# 方法2:導入特定函數
from math_utils import add, PI
result = add(10, 20)
print(f"PI = {PI}")# 方法3:導入并重命名
import math_utils as mu
from math_utils import Calculator as Calccalc = Calc()
result = calc.calculate('add', 1, 2)# 方法4:導入所有(不推薦)
# from math_utils import *# 查看模塊信息
print(f"模塊名稱: {math_utils.__name__}")
print(f"模塊文件: {math_utils.__file__}")
print(f"模塊文檔: {math_utils.__doc__}")
print(f"模塊屬性: {dir(math_utils)}")

包(Package)

# 包的結構示例
"""
mypackage/__init__.pymodule1.pymodule2.pysubpackage/__init__.pysubmodule.py
"""# mypackage/__init__.py
"""這是一個示例包"""__version__ = "1.0.0"
__author__ = "Your Name"# 控制 from mypackage import * 的行為
__all__ = ['module1', 'important_function']from .module1 import important_function
from .module2 import AnotherClass# 包級別的初始化代碼
print(f"正在初始化包 {__name__}")# mypackage/module1.py
def important_function():return "這是一個重要的函數"def helper_function():return "這是一個輔助函數"# mypackage/module2.py
class AnotherClass:def __init__(self):self.value = "Another Class"# mypackage/subpackage/__init__.py
from .submodule import SubFunction# mypackage/subpackage/submodule.py
def SubFunction():return "子包中的函數"# 使用包
import mypackage
from mypackage import module1
from mypackage.subpackage import SubFunction# 相對導入(在包內部使用)
# from . import module1          # 同級導入
# from ..module1 import func     # 上級導入
# from .subpackage import sub    # 子包導入# 動態導入
import importlibmodule_name = "math"
math_module = importlib.import_module(module_name)
print(f"π = {math_module.pi}")# 檢查模塊是否存在
try:import some_optional_module
except ImportError:print("可選模塊不存在")some_optional_module = None# 模塊搜索路徑
import sys
print("Python模塊搜索路徑:")
for path in sys.path:print(f"  {path}")# 添加自定義路徑
sys.path.append('/path/to/custom/modules')# 重新加載模塊(開發時有用)
importlib.reload(math_utils)

24. 什么是asyncio?它有什么用途?

import asyncio
import aiohttp
import time
from concurrent.futures import ThreadPoolExecutor# 基本的異步函數
async def hello_async():print("Hello")await asyncio.sleep(1)  # 異步等待print("World")# 運行異步函數
# asyncio.run(hello_async())# 并發執行多個異步任務
async def fetch_data(url, session):async with session.get(url) as response:return await response.text()async def main():urls = ['https://httpbin.org/delay/1','https://httpbin.org/delay/2','https://httpbin.org/delay/1']async with aiohttp.ClientSession() as session:# 并發執行tasks = [fetch_data(url, session) for url in urls]results = await asyncio.gather(*tasks)return results# 異步生成器
async def async_generator():for i in range(5):await asyncio.sleep(0.1)yield iasync def consume_async_generator():async for value in async_generator():print(f"Generated: {value}")# 異步上下文管理器
class AsyncContextManager:async def __aenter__(self):print("進入異步上下文")await asyncio.sleep(0.1)return selfasync def __aexit__(self, exc_type, exc_val, exc_tb):print("退出異步上下文")await asyncio.sleep(0.1)async def use_async_context():async with AsyncContextManager() as cm:print("在異步上下文中")await asyncio.sleep(0.5)# 異步隊列
async def producer(queue):for i in range(5):await asyncio.sleep(0.1)await queue.put(f"item-{i}")print(f"生產: item-{i}")await queue.put(None)  # 結束信號async def consumer(queue):while True:item = await queue.get()if item is None:breakprint(f"消費: {item}")await asyncio.sleep(0.2)queue.task_done()async def producer_consumer_example():queue = asyncio.Queue(maxsize=3)# 創建生產者和消費者任務producer_task = asyncio.create_task(producer(queue))consumer_task = asyncio.create_task(consumer(queue))# 等待生產者完成await producer_task# 等待隊列中的所有任務完成await queue.join()# 取消消費者任務consumer_task.cancel()# 異步鎖
shared_resource = 0
lock = asyncio.Lock()async def modify_shared_resource(name):global shared_resourceasync with lock:print(f"{name} 獲得鎖")temp = shared_resourceawait asyncio.sleep(0.1)  # 模擬處理時間shared_resource = temp + 1print(f"{name} 釋放鎖,資源值: {shared_resource}")async def lock_example():tasks = [modify_shared_resource("Task-1"),modify_shared_resource("Task-2"),modify_shared_resource("Task-3")]await asyncio.gather(*tasks)# 超時處理
async def slow_operation():await asyncio.sleep(3)return "操作完成"async def timeout_example():try:result = await asyncio.wait_for(slow_operation(), timeout=2)print(result)except asyncio.TimeoutError:print("操作超時")# 事件循環控制
async def event_loop_example():loop = asyncio.get_event_loop()# 在線程池中運行阻塞操作def blocking_operation():time.sleep(1)return "阻塞操作完成"result = await loop.run_in_executor(None, blocking_operation)print(result)# 調度回調def callback():print("回調函數執行")loop.call_later(1, callback)await asyncio.sleep(1.1)# 性能對比:同步 vs 異步
def sync_fetch(url):# 模擬網絡請求time.sleep(1)return f"Data from {url}"async def async_fetch(url):# 模擬異步網絡請求await asyncio.sleep(1)return f"Data from {url}"def compare_performance():urls = [f"url-{i}" for i in range(5)]# 同步方式start = time.time()sync_results = [sync_fetch(url) for url in urls]sync_time = time.time() - start# 異步方式async def async_main():tasks = [async_fetch(url) for url in urls]return await asyncio.gather(*tasks)start = time.time()async_results = asyncio.run(async_main())async_time = time.time() - startprint(f"同步執行時間: {sync_time:.2f}秒")print(f"異步執行時間: {async_time:.2f}秒")print(f"性能提升: {sync_time/async_time:.2f}倍")# 運行示例
if __name__ == "__main__":# asyncio.run(hello_async())# asyncio.run(consume_async_generator())# asyncio.run(use_async_context())# asyncio.run(producer_consumer_example())# asyncio.run(lock_example())# asyncio.run(timeout_example())# asyncio.run(event_loop_example())compare_performance()

25. 什么是協程?

import asyncio
import inspect
from types import GeneratorType, CoroutineType# 生成器函數(早期協程的基礎)
def generator_function():print("生成器開始")yield 1print("生成器繼續")yield 2print("生成器結束")return "完成"# 基于生成器的協程(Python 3.4風格)
@asyncio.coroutine
def old_style_coroutine():print("舊式協程開始")yield from asyncio.sleep(1)print("舊式協程結束")return "舊式協程完成"# 原生協程(Python 3.5+推薦)
async def native_coroutine():print("原生協程開始")await asyncio.sleep(1)print("原生協程結束")return "原生協程完成"# 協程的狀態
async def coroutine_states():print("協程狀態演示")# 創建協程對象coro = native_coroutine()print(f"協程類型: {type(coro)}")print(f"是否為協程: {inspect.iscoroutine(coro)}")# 運行協程result = await coroprint(f"協程結果: {result}")# 協程的生命周期
class CoroutineLifecycle:def __init__(self, name):self.name = nameasync def __aenter__(self):print(f"{self.name}: 進入協程上下文")return selfasync def __aexit__(self, exc_type, exc_val, exc_tb):print(f"{self.name}: 退出協程上下文")async def work(self):print(f"{self.name}: 開始工作")await asyncio.sleep(0.5)print(f"{self.name}: 工作完成")async def lifecycle_demo():async with CoroutineLifecycle("Worker-1") as worker:await worker.work()# 協程的異常處理
async def error_coroutine():await asyncio.sleep(0.1)raise ValueError("協程中的錯誤")async def handle_coroutine_error():try:await error_coroutine()except ValueError as e:print(f"捕獲到協程異常: {e}")# 協程的取消
async def cancellable_coroutine():try:print("可取消協程開始")await asyncio.sleep(5)  # 長時間運行print("可取消協程完成")except asyncio.CancelledError:print("協程被取消")raise  # 重新拋出取消異常async def cancel_demo():task = asyncio.create_task(cancellable_coroutine())# 等待1秒后取消await asyncio.sleep(1)task.cancel()try:await taskexcept asyncio.CancelledError:print("任務已被取消")# 協程的組合
async def step1():print("執行步驟1")await asyncio.sleep(0.5)return "步驟1完成"async def step2(result1):print(f"執行步驟2,接收: {result1}")await asyncio.sleep(0.5)return "步驟2完成"async def step3(result2):print(f"執行步驟3,接收: {result2}")await asyncio.sleep(0.5)return "步驟3完成"async def sequential_coroutines():"""順序執行協程"""result1 = await step1()result2 = await step2(result1)result3 = await step3(result2)return result3async def parallel_coroutines():"""并行執行協程"""results = await asyncio.gather(step1(),step1(),  # 可以同時執行多個相同的協程step1())return results# 協程與線程的對比
import threading
import timedef thread_function(name, duration):print(f"線程 {name} 開始")time.sleep(duration)print(f"線程 {name} 結束")async def coroutine_function(name, duration):print(f"協程 {name} 開始")await asyncio.sleep(duration)print(f"協程 {name} 結束")def compare_thread_vs_coroutine():# 線程方式start = time.time()threads = []for i in range(3):t = threading.Thread(target=thread_function, args=(f"Thread-{i}", 1))threads.append(t)t.start()for t in threads:t.join()thread_time = time.time() - start# 協程方式async def coroutine_main():tasks = [coroutine_function(f"Coroutine-{i}", 1) for i in range(3)]await asyncio.gather(*tasks)start = time.time()asyncio.run(coroutine_main())coroutine_time = time.time() - startprint(f"線程執行時間: {thread_time:.2f}秒")print(f"協程執行時間: {coroutine_time:.2f}秒")# 運行示例
if __name__ == "__main__":# asyncio.run(hello_async())# asyncio.run(consume_async_generator())# asyncio.run(use_async_context())# asyncio.run(producer_consumer_example())# asyncio.run(lock_example())# asyncio.run(timeout_example())# asyncio.run(event_loop_example())compare_performance()

26. 協程和線程的區別

特性協程(Coroutine)線程(Thread)
調度方式協作式調度搶占式調度
切換開銷極低較高
內存占用很小(KB級別)較大(MB級別)
并發數量可達數萬個通常數百個
同步機制無需鎖需要鎖機制
CPU密集型不適合適合
I/O密集型非常適合適合
import asyncio
import threading
import time
import concurrent.futures# 協程示例
async def async_io_task(task_id):print(f"異步任務 {task_id} 開始")await asyncio.sleep(1)  # 模擬I/O操作print(f"異步任務 {task_id} 完成")return f"結果-{task_id}"# 線程示例
def thread_io_task(task_id):print(f"線程任務 {task_id} 開始")time.sleep(1)  # 模擬I/O操作print(f"線程任務 {task_id} 完成")return f"結果-{task_id}"# 性能對比
def performance_comparison():num_tasks = 10# 協程性能測試async def async_test():tasks = [async_io_task(i) for i in range(num_tasks)]return await asyncio.gather(*tasks)start = time.time()async_results = asyncio.run(async_test())async_time = time.time() - start# 線程性能測試start = time.time()with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:thread_results = list(executor.map(thread_io_task, range(num_tasks)))thread_time = time.time() - startprint(f"協程執行 {num_tasks} 個任務耗時: {async_time:.2f}秒")print(f"線程執行 {num_tasks} 個任務耗時: {thread_time:.2f}秒")# 內存使用對比import psutilimport osprocess = psutil.Process(os.getpid())print(f"當前進程內存使用: {process.memory_info().rss / 1024 / 1024:.2f} MB")# 協程的適用場景
async def web_scraping_example():"""網絡爬蟲場景"""import aiohttpurls = ['https://httpbin.org/delay/1','https://httpbin.org/delay/1','https://httpbin.org/delay/1']async def fetch(session, url):async with session.get(url) as response:return await response.text()async with aiohttp.ClientSession() as session:tasks = [fetch(session, url) for url in urls]results = await asyncio.gather(*tasks)return results# 線程的適用場景
def cpu_intensive_task(n):"""CPU密集型任務"""result = 0for i in range(n):result += i * ireturn resultdef cpu_intensive_comparison():num_tasks = 4task_size = 1000000# 單線程start = time.time()single_results = [cpu_intensive_task(task_size) for _ in range(num_tasks)]single_time = time.time() - start# 多線程start = time.time()with concurrent.futures.ThreadPoolExecutor() as executor:multi_results = list(executor.map(cpu_intensive_task, [task_size] * num_tasks))multi_time = time.time() - startprint(f"單線程CPU密集型任務耗時: {single_time:.2f}秒")print(f"多線程CPU密集型任務耗時: {multi_time:.2f}秒")print(f"性能提升: {single_time/multi_time:.2f}倍")

27. Future和Task的區別

import asyncio
from concurrent.futures import ThreadPoolExecutor, Future as ThreadFuture# asyncio.Future
async def future_example():loop = asyncio.get_event_loop()# 創建Future對象future = loop.create_future()# 在另一個協程中設置結果async def set_result():await asyncio.sleep(1)future.set_result("Future的結果")# 啟動設置結果的協程asyncio.create_task(set_result())# 等待Future完成result = await futureprint(f"Future結果: {result}")# asyncio.Task
async def task_example():async def background_task():await asyncio.sleep(2)return "Task的結果"# 創建Tasktask = asyncio.create_task(background_task())# Task的狀態print(f"Task創建后狀態: {task.done()}")# 等待Task完成result = await taskprint(f"Task結果: {result}")print(f"Task完成后狀態: {task.done()}")# Future vs Task 對比
async def future_vs_task():loop = asyncio.get_event_loop()# Future: 低級別的可等待對象future = loop.create_future()# Task: 對協程的封裝async def coro():return "協程結果"task = asyncio.create_task(coro())# 手動設置Future的結果future.set_result("手動設置的結果")# 等待兩者完成future_result = await futuretask_result = await taskprint(f"Future結果: {future_result}")print(f"Task結果: {task_result}")# Task的生命周期管理
async def task_lifecycle():async def long_running_task():try:for i in range(10):print(f"任務進度: {i+1}/10")await asyncio.sleep(0.5)return "任務完成"except asyncio.CancelledError:print("任務被取消")raise# 創建并啟動任務task = asyncio.create_task(long_running_task())# 等待一段時間后取消await asyncio.sleep(2)task.cancel()try:result = await taskexcept asyncio.CancelledError:print("確認任務已取消")# 并發控制
async def concurrent_control():async def worker(name, duration):print(f"工作者 {name} 開始")await asyncio.sleep(duration)print(f"工作者 {name} 完成")return f"結果-{name}"# 創建多個任務tasks = [asyncio.create_task(worker(f"Worker-{i}", i+1))for i in range(3)]# 等待第一個完成done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)print(f"第一個完成的任務: {done}")# 取消剩余任務for task in pending:task.cancel()# 等待所有任務結束await asyncio.gather(*pending, return_exceptions=True)

28. Python中的元類(Metaclass)

# 元類的基本概念
class MyMetaclass(type):def __new__(mcs, name, bases, attrs):print(f"創建類 {name}")# 自動為所有方法添加日志for key, value in attrs.items():if callable(value) and not key.startswith('__'):attrs[key] = MyMetaclass.add_logging(value)return super().__new__(mcs, name, bases, attrs)@staticmethoddef add_logging(func):def wrapper(*args, **kwargs):print(f"調用方法: {func.__name__}")return func(*args, **kwargs)return wrapperclass MyClass(metaclass=MyMetaclass):def method1(self):return "方法1"def method2(self):return "方法2"# 單例元類
class SingletonMeta(type):_instances = {}def __call__(cls, *args, **kwargs):if cls not in cls._instances:cls._instances[cls] = super().__call__(*args, **kwargs)return cls._instances[cls]class Database(metaclass=SingletonMeta):def __init__(self):self.connection = "數據庫連接"# 屬性驗證元類
class ValidatedMeta(type):def __new__(mcs, name, bases, attrs):# 為所有屬性添加類型檢查for key, value in attrs.items():if isinstance(value, type):attrs[f'_{key}'] = Noneattrs[key] = mcs.create_property(key, value)return super().__new__(mcs, name, bases, attrs)@staticmethoddef create_property(name, expected_type):def getter(self):return getattr(self, f'_{name}')def setter(self, value):if not isinstance(value, expected_type):raise TypeError(f"{name} 必須是 {expected_type.__name__} 類型")setattr(self, f'_{name}', value)return property(getter, setter)class Person(metaclass=ValidatedMeta):name = strage = intdef __init__(self, name, age):self.name = nameself.age = age

29. Python中的描述符(Descriptor)

# 描述符協議
class LoggedAttribute:def __init__(self, name):self.name = nameself.value = Nonedef __get__(self, obj, objtype=None):print(f"獲取屬性 {self.name}: {self.value}")return self.valuedef __set__(self, obj, value):print(f"設置屬性 {self.name}: {value}")self.value = valuedef __delete__(self, obj):print(f"刪除屬性 {self.name}")self.value = None# 類型檢查描述符
class TypedAttribute:def __init__(self, expected_type):self.expected_type = expected_typeself.value = Nonedef __set_name__(self, owner, name):self.name = namedef __get__(self, obj, objtype=None):if obj is None:return selfreturn getattr(obj, f'_{self.name}', None)def __set__(self, obj, value):if not isinstance(value, self.expected_type):raise TypeError(f"{self.name} 必須是 {self.expected_type.__name__} 類型")setattr(obj, f'_{self.name}', value)# 范圍檢查描述符
class RangeAttribute:def __init__(self, min_value, max_value):self.min_value = min_valueself.max_value = max_valuedef __set_name__(self, owner, name):self.name = namedef __get__(self, obj, objtype=None):if obj is None:return selfreturn getattr(obj, f'_{self.name}', None)def __set__(self, obj, value):if not (self.min_value <= value <= self.max_value):raise ValueError(f"{self.name} 必須在 {self.min_value}{self.max_value} 之間")setattr(obj, f'_{self.name}', value)class Student:name = TypedAttribute(str)age = RangeAttribute(0, 150)score = RangeAttribute(0, 100)def __init__(self, name, age, score):self.name = nameself.age = ageself.score = score

30. Python中的上下文變量(Context Variables)

import contextvars
import asyncio# 創建上下文變量
user_id = contextvars.ContextVar('user_id')
request_id = contextvars.ContextVar('request_id', default='unknown')# 上下文變量的使用
def get_current_user():return user_id.get()def get_request_id():return request_id.get()async def process_request(uid, rid):# 設置上下文變量user_id.set(uid)request_id.set(rid)print(f"處理請求 - 用戶: {get_current_user()}, 請求ID: {get_request_id()}")# 調用其他函數,它們可以訪問上下文變量await business_logic()await log_operation()async def business_logic():print(f"業務邏輯 - 當前用戶: {get_current_user()}")await asyncio.sleep(0.1)async def log_operation():print(f"記錄日志 - 用戶: {get_current_user()}, 請求: {get_request_id()}")# 上下文變量的隔離
async def context_isolation_demo():# 并發處理多個請求await asyncio.gather(process_request("user1", "req1"),process_request("user2", "req2"),process_request("user3", "req3"))# 手動管理上下文
def manual_context_management():# 復制當前上下文ctx = contextvars.copy_context()# 在新上下文中運行def run_in_context():user_id.set("context_user")print(f"上下文中的用戶: {get_current_user()}")ctx.run(run_in_context)# 原上下文不受影響try:print(f"原上下文用戶: {get_current_user()}")except LookupError:print("原上下文中沒有設置用戶")

總結

Python面試中的基礎知識涵蓋了語言的核心特性和高級概念。掌握這些知識點不僅有助于通過面試,更重要的是能夠寫出更高質量、更Pythonic的代碼。

重點掌握的概念:

  1. 數據結構:列表、字典、元組的內存管理和性能特點
  2. 函數式編程:閉包、裝飾器、高階函數的應用
  3. 面向對象:繼承、多態、元類、描述符的深入理解
  4. 異步編程:協程、事件循環、并發控制的實踐
  5. 內存管理:深淺拷貝、垃圾回收、引用計數的機制
  6. 高級特性:上下文管理器、生成器、迭代器的使用

面試建議:

  • 理論與實踐結合:不僅要知道概念,還要能寫出代碼示例
  • 性能意識:了解不同實現方式的時間和空間復雜度
  • 最佳實踐:遵循PEP 8規范,寫出Pythonic的代碼
  • 實際應用:能夠將這些知識點應用到實際項目中
希望這份匯總能夠幫助大家在Python面試中取得好成績!

相關文章推薦:

  • Python面試之基礎知識常見面試題1-基礎篇:點我跳轉
  • Python面試之基礎知識常見面試題2-列表篇:點我跳轉

結尾

  • 希望對初學者有幫助;致力于辦公自動化的小小程序員一枚

  • 希望能得到大家的【??一個免費關注??】感謝!

  • 求個 🤞 關注 🤞 +?? 喜歡 ?? +👍 收藏 👍

  • 此外還有辦公自動化專欄,歡迎大家訂閱:Python辦公自動化專欄

  • 此外還有爬蟲專欄,歡迎大家訂閱:Python爬蟲基礎專欄

  • 此外還有Python基礎專欄,歡迎大家訂閱:Python基礎學習專欄

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/87480.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/87480.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/87480.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

【免費.NET方案】CSV到PDF與DataTable的快速轉換

CSV作為輕量級數據載體&#xff0c;在數據傳輸中占比超過70%。但其原生格式存在三大痛點&#xff1a; 可視化缺陷&#xff1a;無法直接生成可打印的報表結構限制&#xff1a;缺乏數據類型定義和關系約束安全風險&#xff1a;易被意外修改導致數據失真 因此&#xff0c;我們常…

connect的斷線重連

connect的短線重連 客戶端代碼的編寫服務器代碼的編寫總結 客戶端代碼的編寫 #include <iostream> #include <string> #include <cstring> #include <cstdlib> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h>…

通過觀看數百個外科手術視頻講座來學習多模態表征|文獻速遞-最新論文分享

Title題目Learning multi-modal representations by watching hundreds of surgical video lectures通過觀看數百個外科手術視頻講座來學習多模態表征01文獻速遞介紹外科計算機視覺領域的最新進展&#xff0c;已開始為手術室&#xff08;OR&#xff09;的新一代人工智能輔助支…

微信小程序如何實現再多個頁面共享數據

在微信小程序中&#xff0c;實現多個頁面共享數據有以下幾種常用方式&#xff0c;根據場景選擇最適合的方案&#xff1a; 全局變量&#xff08;App.js&#xff09; 適用場景&#xff1a;簡單數據共享&#xff08;非響應式&#xff09; 實現方式&#xff1a; javascript // ap…

PCIE5.0 TAG說明(ima回答)

在PCIe 5.0規范中&#xff0c;TLP&#xff08;Transaction Layer Packet&#xff09;報文的Tag字段用于標識和管理事務。以下是關于Tag的生成和使用規則和定義的詳細描述&#xff1a; Tag字段的定義 Tag字段&#xff1a;位于TLP報文的Header中&#xff0c;占用8位&#xff08…

Type-C PD快充協議智能芯片S312L詳解

1. 芯片概述 S312L 是一款智能Type-C PD協議觸發芯片&#xff0c;支持**PD3.0&#xff08;含PPS&#xff09;**及多種A口快充協議&#xff08;如QC/PE等&#xff09;&#xff0c;可自動識別并申請5V/9V/12V電壓&#xff0c;適用于快充適配器、移動電源等場景。 核心優勢&…

stm32學到什么程度可以找工作?

我重新為你寫一篇更加詳細深入的回答&#xff1a; STM32學到什么程度可以找工作&#xff1f;一個十年老兵的血淚史 寫在前面的話&#xff1a;這些年踩過的坑&#xff0c;都是血淋淋的教訓 剛看到這個問題&#xff0c;我就想起了2014年那個炎熱的夏天。 當時我剛從廈門某馬離…

基于 Elasticsearch 實現地圖點聚合

在地圖類應用中&#xff0c;當需要展示大量地理興趣點時&#xff0c;直接將所有點渲染在地圖上會導致視覺混亂&#xff0c;影響用戶體驗。為此&#xff0c;我基于 Elasticsearch 提供的 geotile_grid 和 geo_bounding_box 查詢能力&#xff0c;實現了一套高效的 POI 聚合展示方…

【Prometheus 】通過 Pushgateway 上報指標數據

Prometheus 是目前最流行的開源監控系統之一&#xff0c;其拉取&#xff08;pull&#xff09;模型非常適合服務發現和靜態目標的監控。然而&#xff0c;在某些場景下&#xff0c;例如短生命周期任務、批處理作業或無法暴露 HTTP 接口的服務&#xff0c;傳統的拉取方式并不適用。…

服務器 - - QPS與TPS介紹

1、QPS&#xff08;Queries Per Second 每秒查詢數&#xff09; 定義&#xff1a;常用于表示每秒的請求次數&#xff0c;衡量接口請求、數據庫查詢等動作的吞吐量&#xff08;單位時間內處理的數據量&#xff09; 計算&#xff1a;總請求數/請求時間&#xff0c;如&#xff1…

Cot2:思維鏈提示激發大型語言模型的推理能力

摘要 我們探討了生成思維鏈——一系列中間推理步驟——如何顯著提升大型語言模型執行復雜推理的能力。特別地&#xff0c;我們展示了在足夠大的語言模型中&#xff0c;這種推理能力如何通過一種簡單的方法——思維鏈提示&#xff08;chain-of-thought prompting&#xff09;自…

go交易數據后端

地址 https://gitee.com/EEPPEE_admin/go-stock-line-trading-datahttps://github.com/jerryshell/midas 需求 為了替代rust后端爬蟲端: 爬取東方財富數據到index-data目錄server端: 項目主要內容 todo 替代https://github.com/jerryshell/midas的前端量化概念性理解擴展: 存儲…

靈巧手概覽

第一章 靈巧手的技術演進與核心價值 1.1 技術演進的五個階段 仿生學啟蒙階段&#xff08;1960-1980&#xff09; 1968年斯坦福大學首臺3自由度機械夾爪標志機器人操作技術開端&#xff0c;1973年MIT提出"仿生手"概念&#xff0c;但受限于材料和控制技術&#xff0c;…

在設計提示詞(Prompt)時,關于信息位置的安排z怎么 結合模型特性和任務目標

在設計提示詞(Prompt)時,關于信息位置的安排z怎么 結合模型特性和任務目標 在設計提示詞(Prompt)時,關于信息位置的安排確實需要結合模型特性和任務目標。從自注意力機制的原理及應用場景來看,關鍵信息的位置選擇需遵循以下啟示,并結合具體場景靈活調整: 一、核心啟示…

七、性能優化

目錄 1. 如何檢測Flutter應用的性能問題&#xff1f;2. 什么是重繪邊界&#xff08;Repaint Boundary&#xff09;&#xff1f;3. 如何避免不必要的重建&#xff1f;4. const 構造函數在優化中起什么作用&#xff1f;5. 如何優化長列表的性能&#xff1f;6. 如何減少應用啟動時…

Webpack優化詳解

Webpack 5提供了一系列工具和功能,可以在本地開發和線上構建過程中進行優化,以提高開發效率和構建性能。 1. 本地開發優化 1.1. 開啟模塊熱替換(HMR) 模塊熱替換可以在不刷新整個頁面的情況下更新模塊,提高開發效率。 const webpack = require(webpack);module.export…

latency 對功耗的影響

文章目錄 1、Connection Interval(連接間隔) vs. Latency(從機延遲)2、為什么不能完全依賴 Connection Interval?3、什么時候可以不用 Latency?4、如何正確配置?5、結論調節連接間隔(Connection Interval)確實可以直接影響通信頻率和功耗,但 Latency(從機延遲)仍然…

10分鐘搭建 PHP 開發環境教程

下載、安裝 Xserver 下載 php 過程中如果提示需要安裝 vc 運行環境&#xff0c;按照引導下載安裝即可 安裝 nginx 安裝 Mysql 支持多個版本同時安裝 下載 php 過程中如果提示需要安裝 vc 運行環境&#xff0c;按照引導下載安裝即可mysql 默認用戶名為 root&#xff0c;默認密…

設計模式(六)

備忘錄模式&#xff08;Memento Pattern&#xff09;詳解 一、核心概念 備忘錄模式允許在不破壞封裝性的前提下&#xff0c;捕獲并保存對象的內部狀態&#xff0c;以便后續恢復。該模式通過三個角色實現&#xff1a; 原發器&#xff08;Originator&#xff09;&#xff1a;需…

迪杰斯特拉算法之解決單源最短路徑問題

迪杰斯特拉算法 迪杰斯特拉(Dijkstra)算法是典型**最短路徑算法**&#xff0c;用于計算一個結點到其它結點的最短路徑。它的主要特點是以起始點為中心向外擴展(利用廣度優先搜索思想)&#xff0c;直到擴展到終點。迪杰斯特拉(Dijkstra)算法最佳應用-最短路徑 戰爭時期&#xf…