
Python开发中,掌握一些高效的方法和技巧可以显著提升编码速度、代码可读性和维护性。本文介绍50个实用的Python技巧,涵盖数据处理、代码优化、调试等多个方面,帮助成为更高效的Python开发者。
使用场景:快速生成列表,替代传统的for循环。
说明:列表推导式提供了一种简洁的方式来创建列表,通常比for循环更高效。
代码示例:
# 传统方法
squares = []
for i in range(10):
squares.append(i**2)
# 列表推导式
squares = [i**2 for i in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]使用场景:处理大量数据时节省内存。
说明:生成器表达式类似于列表推导式,但返回一个生成器对象,只在需要时生成值。
代码示例:
# 列表推导式(占用内存)
data = [x**2 for x in range(1000000)]
# 生成器表达式(节省内存)
data_gen = (x**2 for x in range(1000000))
for value in data_gen:
if value > 100:
break
print(value)使用场景:在循环中需要同时访问索引和元素。
说明: enumerate() 函数返回一个包含索引和值的元组。
代码示例:
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"索引 {index}: {fruit}")使用场景:需要同时处理多个列表或迭代器。
说明: zip() 函数将多个可迭代对象组合成一个元组序列。
代码示例:
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")使用场景:需要为字典的缺失键提供默认值。
说明: defaultdict 在键不存在时自动创建默认值。
代码示例:
from collections import defaultdict
# 传统方法
word_count = {}
for word in ['apple', 'banana', 'apple', 'cherry']:
if word not in word_count:
word_count[word] = 0
word_count[word] += 1
# 使用defaultdict
word_count = defaultdict(int)
for word in ['apple', 'banana', 'apple', 'cherry']:
word_count[word] += 1
print(dict(word_count)) # 输出: {'apple': 2, 'banana': 1, 'cherry': 1}使用场景:统计元素出现频率。
说明: Counter 是专门为计数设计的字典子类。
代码示例:
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts.most_common(2)) # 输出: [('apple', 3), ('banana', 2)]使用场景:需要将变量嵌入字符串中。
说明:f-string提供了一种更简洁、更易读的字符串格式化方式。
代码示例:
name = "Alice"
age = 25
# 传统方法
message = "{} is {} years old".format(name, age)
# f-string
message = f"{name} is {age} years old"
print(message) # 输出: Alice is 25 years old使用场景:需要跨平台处理文件路径。
说明: pathlib 提供了面向对象的路径操作方式。
代码示例:
from pathlib import Path
# 创建路径对象
current_dir = Path.cwd()
file_path = current_dir / "data" / "file.txt"
# 检查文件是否存在
if file_path.exists():
print(f"文件大小: {file_path.stat().st_size} bytes")使用场景:需要管理资源(如文件、数据库连接)的打开和关闭。
说明: contextlib 模块提供了创建上下文管理器的简便方法。
代码示例:
from contextlib import contextmanager
@contextmanager
def open_file(filename, mode):
file = open(filename, mode)
try:
yield file
finally:
file.close()
# 使用自定义上下文管理器
with open_file('example.txt', 'w') as f:
f.write('Hello, World!')使用场景:创建主要存储数据的类。
说明: dataclass 装饰器自动生成特殊方法如 init 、 repr 等。
代码示例:
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
city: str = "Unknown"
person = Person("Alice", 25)
print(person) # 输出: Person(name='Alice', age=25, city='Unknown')使用场景:需要复杂的迭代操作。
说明: itertools 模块提供了许多高效的迭代工具。
代码示例:
import itertools
# 无限计数器
counter = itertools.count(start=10, step=2)
print(next(counter)) # 输出: 10
print(next(counter)) # 输出: 12
# 排列组合
letters = ['A', 'B', 'C']
combinations = list(itertools.combinations(letters, 2))
print(combinations) # 输出: [('A', 'B'), ('A', 'C'), ('B', 'C')]使用场景:函数调用开销大且经常被相同参数调用。
说明: lru_cache 装饰器缓存函数调用结果,避免重复计算。
代码示例:
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(30)) # 快速计算,结果被缓存使用场景:需要从序列中提取多个值。
说明:Python支持序列解包,可以一次性分配多个变量。
代码示例:
# 基本解包
a, b, c = [1, 2, 3]
print(a, b, c) # 输出: 1 2 3
# 扩展解包
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 输出: 1
print(middle) # 输出: [2, 3, 4]
print(last) # 输出: 5使用场景:需要在表达式中进行赋值。
说明:Python 3.8引入的海象运算符 := 允许在表达式中进行赋值。
代码示例:
# 基本解包
a, b, c = [1, 2, 3]
print(a, b, c) # 输出: 1 2 3
# 扩展解包
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 输出: 1
print(middle) # 输出: [2, 3, 4]
print(last) # 输出: 5使用场景:需要检查可迭代对象中是否满足某些条件。
说明: any() 检查是否有任意元素为True, all() 检查是否所有元素都为True。
代码示例:
numbers = [1, 2, 3, 4, 5]
# 检查是否有偶数
has_even = any(n % 2 == 0 for n in numbers)
print(has_even) # 输出: True
# 检查是否都是正数
all_positive = all(n > 0 for n in numbers)
print(all_positive) # 输出: True使用场景:需要频繁检查元素是否存在于集合中。
说明:集合的成员检查时间复杂度为O(1),比列表的O(n)快得多。
代码示例:
# 列表(慢)
items_list = ['apple', 'banana', 'cherry', 'date', 'elderberry']
if 'cherry' in items_list: # O(n)
print("Found!")
# 集合(快)
items_set = {'apple', 'banana', 'cherry', 'date', 'elderberry'}
if 'cherry' in items_set: # O(1)
print("Found!")使用场景:需要从其他数据结构快速创建字典。
说明:类似于列表推导式,但用于创建字典。
代码示例:
# 传统方法
squares = {}
for i in range(5):
squares[i] = i**2
# 字典推导式
squares = {i: i**2 for i in range(5)}
print(squares) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}使用场景:需要从字典中获取值,但键可能不存在。
说明: get() 方法在键不存在时返回默认值,避免KeyError。
代码示例:
user = {'name': 'Alice', 'age': 25}
# 传统方法(可能引发KeyError)
if 'email' in user:
email = user['email']
else:
email = 'default@example.com'
# 使用get()方法
email = user.get('email', 'default@example.com')
print(email) # 输出: default@example.com使用场景:需要将多个字典作为一个视图访问。
说明: ChainMap 将多个字典链接在一起,按顺序查找键。
代码示例:
from collections import ChainMap
default_config = {'theme': 'light', 'language': 'en'}
user_config = {'theme': 'dark'}
system_config = {'timeout': 30}
config = ChainMap(user_config, default_config, system_config)
print(config['theme']) # 输出: dark (来自user_config)
print(config['language']) # 输出: en (来自default_config)
print(config['timeout']) # 输出: 30 (来自system_config)使用场景:需要创建简单的数据对象,但不想定义完整的类。
说明: namedtuple 创建具有字段名的元组子类。
代码示例:
from collections import namedtuple
# 定义Point类
Point = namedtuple('Point', ['x', 'y'])
# 创建Point实例
p = Point(10, 20)
print(p.x, p.y) # 输出: 10 20
print(p[0], p[1](@ref) # 输出: 10 20 (仍然可以按索引访问)使用场景:需要创建带有预设参数的函数版本。
说明: functools.partial 可以固定函数的部分参数。
代码示例:
from functools import partial
def power(base, exponent):
return base ** exponent
# 创建平方函数
square = partial(power, exponent=2)
print(square(5)) # 输出: 25
# 创建立方函数
cube = partial(power, exponent=3)
print(cube(3)) # 输出: 27使用场景:需要将操作符作为函数使用。
说明: operator 模块提供了对应Python操作符的函数。
代码示例:
import operator
numbers = [1, 2, 3, 4, 5]
# 使用operator.add代替lambda
sum_result = sum(numbers)
product = 1
for num in numbers:
product = operator.mul(product, num)
print(f"和: {sum_result}, 积: {product}") # 输出: 和: 15, 积: 120使用场景:需要在有序序列中快速查找或插入元素。
说明: bisect 模块提供了二分查找算法。
代码示例:
import bisect
sorted_list = [1, 3, 5, 7, 9]
# 查找插入位置以保持有序
position = bisect.bisect_left(sorted_list, 6)
print(f"插入位置: {position}") # 输出: 插入位置: 3
# 实际插入
bisect.insort_left(sorted_list, 6)
print(sorted_list) # 输出: [1, 3, 5, 6, 7, 9]使用场景:需要高效获取最大或最小元素。
说明: heapq 模块提供了堆队列算法。
代码示例:
import heapq
numbers = [5, 7, 9, 1, 3]
# 将列表转换为堆
heapq.heapify(numbers)
print(numbers) # 输出: [1, 3, 9, 7, 5]
# 获取最小元素
smallest = heapq.heappop(numbers)
print(f"最小元素: {smallest}") # 输出: 最小元素: 1
print(numbers) # 输出: [3, 5, 9, 7]使用场景:需要读写JSON格式的数据。
说明:Python内置的 json 模块提供了JSON编码和解码功能。
代码示例:
import json
# Python对象转换为JSON字符串
data = {
"name": "Alice",
"age": 25,
"cities": ["New York", "London", "Tokyo"]
}
json_str = json.dumps(data, indent=2)
print(json_str)
# JSON字符串转换为Python对象
parsed_data = json.loads(json_str)
print(parsed_data["name"]) # 输出: Alice使用场景:需要读写CSV格式的数据。
说明:Python内置的 csv 模块提供了CSV文件读写功能。
代码示例:
import csv
# 写入CSV文件
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', '25', 'New York'])
writer.writerow(['Bob', '30', 'London'])
# 读取CSV文件
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)使用场景:需要进行数据清洗、转换和分析。
说明: pandas 是Python中最流行的数据分析库。
代码示例:
import pandas as pd
# 创建DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'London', 'Tokyo']
}
df = pd.DataFrame(data)
# 基本操作
print(df.head())
print(df.describe())
print(df[df['Age'] > 28])使用场景:需要进行大规模数值计算。
说明: numpy 是Python中用于科学计算的基础库。
代码示例:
import numpy as np
# 创建数组
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2) # 输出: [ 2 4 6 8 10]
# 矩阵运算
matrix = np.array([[1, 2], [3, 4]])
print(np.linalg.inv(matrix)) # 计算逆矩阵使用场景:需要进行复杂的文本匹配和提取。
说明:Python的 re 模块提供了正则表达式功能。
代码示例:
import re
text = "Contact us at support@example.com or sales@company.org"
# 提取所有邮箱地址
emails = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', text)
print(emails) # 输出: ['support@example.com', 'sales@company.org']
# 验证邮箱格式
def is_valid_email(email):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return bool(re.match(pattern, email))
print(is_valid_email("test@example.com")) # 输出: True
print(is_valid_email("invalid-email")) # 输出: False使用场景:需要记录程序运行时的信息。
说明:Python的 logging 模块提供了灵活的日志记录系统。
代码示例:
import logging
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='app.log'
)
logger = logging.getLogger(__name__)
# 记录不同级别的日志
logger.debug("调试信息")
logger.info("一般信息")
logger.warning("警告信息")
logger.error("错误信息")
logger.critical("严重错误")使用场景:需要确保代码的正确性。
说明:Python内置的 unittest 模块提供了单元测试框架。
代码示例:
import unittest
def add(a, b):
return a + b
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main()使用场景:需要模拟外部依赖进行测试。
说明: unittest.mock 模块提供了创建模拟对象的功能。
代码示例:
import unittest
def add(a, b):
return a + b
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertEqual(add(-1, 1), 0)
self.assertEqual(add(0, 0), 0)
if __name__ == '__main__':
unittest.main()使用场景:需要在不修改函数代码的情况下增强其功能。
说明:装饰器是修改或增强函数行为的强大工具。
代码示例:
import time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} 执行时间: {end_time - start_time:.4f}秒")
return result
return wrapper
@timer
def slow_function():
time.sleep(2)
return "完成"
result = slow_function()
print(result)使用场景:需要提高代码的可读性和可维护性。
说明:Python 3.5+支持类型提示,帮助开发者和工具理解代码。
代码示例:
from typing import List, Dict, Optional
def process_data(
data: List[int],
config: Optional[Dict[str, str]] = None
) -> Dict[str, float]:
"""处理数据并返回统计结果"""
if config is None:
config = {}
result = {
'mean': sum(data) / len(data),
'max': max(data),
'min': min(data)
}
return result
data = [1, 2, 3, 4, 5]
stats = process_data(data)
print(stats) # 输出: {'mean': 3.0, 'max': 5, 'min': 1}使用场景:需要处理I/O密集型任务。
说明: asyncio 是Python的异步I/O框架。
代码示例:
from typing import List, Dict, Optional
def process_data(
data: List[int],
config: Optional[Dict[str, str]] = None
) -> Dict[str, float]:
"""处理数据并返回统计结果"""
if config is None:
config = {}
result = {
'mean': sum(data) / len(data),
'max': max(data),
'min': min(data)
}
return result
data = [1, 2, 3, 4, 5]
stats = process_data(data)
print(stats) # 输出: {'mean': 3.0, 'max': 5, 'min': 1}使用场景:需要利用多核CPU进行并行计算。
说明: multiprocessing 模块支持真正的并行执行。
代码示例:
import multiprocessing
import time
def process_data(data_chunk):
"""模拟数据处理"""
time.sleep(1) # 模拟耗时操作
return sum(data_chunk)
if __name__ == '__main__':
data = [list(range(i, i+1000)) for i in range(0, 5000, 1000)]
# 串行处理
start_time = time.time()
results_serial = [process_data(chunk) for chunk in data]
serial_time = time.time() - start_time
# 并行处理
start_time = time.time()
with multiprocessing.Pool() as pool:
results_parallel = pool.map(process_data, data)
parallel_time = time.time() - start_time
print(f"串行时间: {serial_time:.2f}秒")
print(f"并行时间: {parallel_time:.2f}秒")
print(f"加速比: {serial_time/parallel_time:.2f}x")使用场景:需要处理I/O密集型任务,但不想使用异步编程。
说明: threading 模块提供了线程级别的并发。
代码示例:
import threading
import time
def download_file(filename):
print(f"开始下载 {filename}")
time.sleep(2) # 模拟下载时间
print(f"完成下载 {filename}")
# 创建多个线程
threads = []
files = ['file1.txt', 'file2.txt', 'file3.txt']
for file in files:
thread = threading.Thread(target=download_file, args=(file,))
threads.append(thread)
thread.start()
# 等待所有线程完成
for thread in threads:
thread.join()
print("所有文件下载完成")使用场景:需要更高级的并发控制。
说明: concurrent.futures 提供了线程和进程池的高级接口。
代码示例:
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def process_item(item):
time.sleep(1) # 模拟处理时间
return f"处理完成: {item}"
items = ['A', 'B', 'C', 'D', 'E']
# 使用线程池
with ThreadPoolExecutor(max_workers=3) as executor:
futures = [executor.submit(process_item, item) for item in items]
for future in as_completed(futures):
result = future.result()
print(result)使用场景:需要在访问属性时添加逻辑。
说明: @property 装饰器可以将方法转换为属性。
代码示例:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("半径不能为负数")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
@property
def circumference(self):
return 2 * 3.14159 * self._radius
circle = Circle(5)
print(f"半径: {circle.radius}") # 输出: 半径: 5
print(f"面积: {circle.area:.2f}") # 输出: 面积: 78.54
print(f"周长: {circle.circumference:.2f}") # 输出: 周长: 31.42
circle.radius = 10
print(f"新面积: {circle.area:.2f}") # 输出: 新面积: 314.16使用场景:需要创建大量实例时优化内存使用。
说明: slots 可以限制实例的属性,减少内存占用。
代码示例:
class PointWithSlots:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
class PointWithoutSlots:
def __init__(self, x, y):
self.x = x
self.y = y
# 测试内存使用
import sys
p1 = PointWithSlots(1, 2)
p2 = PointWithoutSlots(1, 2)
print(f"使用__slots__的内存: {sys.getsizeof(p1)} bytes")
print(f"不使用__slots__的内存: {sys.getsizeof(p2)} bytes")使用场景:需要管理资源的获取和释放。
说明:通过实现 enter 和 exit 方法创建自定义上下文管理器。
代码示例:
class DatabaseConnection:
def __init__(self, database_name):
self.database_name = database_name
self.connection = None
def __enter__(self):
print(f"连接到数据库: {self.database_name}")
self.connection = f"Connection to {self.database_name}"
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print(f"关闭数据库连接: {self.database_name}")
self.connection = None
def execute_query(self, query):
print(f"执行查询: {query}")
return f"Result of {query}"
# 使用上下文管理器
with DatabaseConnection("my_database") as db:
result = db.execute_query("SELECT * FROM users")
print(result)使用场景:需要让自定义类支持索引访问。
说明:通过实现 getitem 和 setitem 方法,可以让对象像列表一样被索引。
代码示例:
class CustomList:
def __init__(self, *args):
self._data = list(args)
def __getitem__(self, index):
return self._data[index]
def __setitem__(self, index, value):
self._data[index] = value
def __len__(self):
return len(self._data)
def __repr__(self):
return f"CustomList({self._data})"
my_list = CustomList(1, 2, 3, 4, 5)
print(my_list[2](@ref) # 输出: 3
my_list[2] = 10
print(my_list) # 输出: CustomList([1, 2, 10, 4, 5])
print(len(my_list)) # 输出: 5使用场景:需要让对象像函数一样被调用。
说明:通过实现 call 方法,可以让对象实例像函数一样被调用。
代码示例:
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
triple = Multiplier(3)
print(double(5)) # 输出: 10
print(triple(5)) # 输出: 15
# 也可以这样使用
multipliers = [Multiplier(i) for i in range(1, 6)]
results = [multiplier(10) for multiplier in multipliers]
print(results) # 输出: [10, 20, 30, 40, 50]使用场景:需要提供对象的字符串表示。
说明: str 用于用户友好的表示, repr 用于开发者友好的表示。
代码示例:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name}, {self.age}岁"
def __repr__(self):
return f"Person(name='{self.name}', age={self.age})"
person = Person("Alice", 25)
print(str(person)) # 输出: Alice, 25岁
print(repr(person)) # 输出: Person(name='Alice', age=25)使用场景:需要让自定义类支持算术运算。
说明:通过实现特殊方法可以重载运算符。
代码示例:
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)
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3)
v2 = Vector(4, 5)
print(v1 + v2) # 输出: Vector(6, 8)
print(v1 - v2) # 输出: Vector(-2, -2)
print(v1 * 3) # 输出: Vector(6, 9)使用场景:需要让自定义类支持迭代。
说明:通过实现 iter 和 next 方法创建迭代器。
代码示例:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value
# 使用迭代器
for number in Countdown(5):
print(number, end=" ") # 输出: 5 4 3 2 1
print()
# 手动使用迭代器
countdown = Countdown(3)
print(next(countdown)) # 输出: 3
print(next(countdown)) # 输出: 2
print(next(countdown)) # 输出: 1使用场景:需要按需生成值,节省内存。
说明:使用 yield 关键字创建生成器函数,可以暂停和恢复执行。
代码示例:
def fibonacci_generator(n):
"""生成斐波那契数列的前n个数"""
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
# 使用生成器
for num in fibonacci_generator(10):
print(num, end=" ") # 输出: 0 1 1 2 3 5 8 13 21 34
print()
# 生成器表达式
squares = (x**2 for x in range(10))
for square in squares:
print(square, end=" ") # 输出: 0 1 4 9 16 25 36 49 64 81使用场景:需要更复杂的生成器控制流。
说明:协程是增强的生成器,可以接收值并保持状态。
代码示例:
def running_average():
"""计算运行平均值"""
total = 0
count = 0
average = 0
while True:
value = yield average
total += value
count += 1
average = total / count
# 使用协程
avg_calculator = running_average()
next(avg_calculator) # 启动协程
print(avg_calculator.send(10)) # 输出: 10.0
print(avg_calculator.send(20)) # 输出: 15.0
print(avg_calculator.send(30)) # 输出: 20.0使用场景:需要对属性访问进行精细控制。
说明:描述符是实现了 get 、set 或 delete 方法的类。
代码示例:
class PositiveNumber:
"""描述符:确保数值为正数"""
def __init__(self, name):
self.name = name
def __get__(self, obj, objtype):
return obj.__dict__.get(self.name, 0)
def __set__(self, obj, value):
if value < 0:
raise ValueError("值必须为正数")
obj.__dict__[self.name] = value
class Rectangle:
width = PositiveNumber('width')
height = PositiveNumber('height')
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
rect = Rectangle(5, 10)
print(f"面积: {rect.area}") # 输出: 面积: 50
try:
rect.width = -5 # 抛出 ValueError
except ValueError as e:
print(f"错误: {e}")使用场景:需要在类创建时进行高级控制。
说明:元类是类的类,控制类的创建行为。
代码示例:
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 DatabaseConnection(metaclass=SingletonMeta):
def __init__(self, connection_string):
self.connection_string = connection_string
print(f"创建数据库连接: {connection_string}")
def query(self, sql):
return f"执行查询: {sql}"
# 测试单例模式
db1 = DatabaseConnection("mysql://localhost/db1")
db2 = DatabaseConnection("mysql://localhost/db2")
print(db1 is db2) # 输出: True (是同一个实例)
print(db1.connection_string) # 输出: mysql://localhost/db1
print(db2.connection_string) # 输出: mysql://localhost/db1将这些技巧应用到实际开发中,能够编写出更高效、更优雅、更可维护的Python代码。
1、提高编码效率:通过掌握简洁的语法和内置功能
2、优化代码性能:使用适当的数据结构和算法
3、增强代码可读性:通过清晰的表达和类型提示
4、改善代码维护性:通过良好的设计和模式
5、扩展Python功能:通过元编程和高级特性
“无他,惟手熟尔”!有需要的用起来!
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!