编程与数学 02-017 Python 面向对象编程 19课题、字符串、序列化和文件路径
摘要:本文介绍了Python面向对象编程中字符串处理、序列化和文件路径操作的高级应用。通过实例展示了如何封装字符串操作、实现序列化与反序列化、以及使用
pathlib
模块进行文件路径管理。同时提供了综合应用示例,如配置文件管理和日志文件轮转器。最后总结了面向对象编程的最佳实践,强调了代码封装、安全性和可读性的重要性。
关键词:Python、面向对象编程、字符串处理、序列化、文件路径、pathlib、JSON、Pickle
人工智能助手:Kimi
一、面向对象编程中的字符串处理
1. 字符串对象基础
在Python中,字符串是不可变序列,属于内置的str
类:
s = "Hello, OOP!"
print(type(s)) # <class 'str'>
2. 常用字符串方法
class TextProcessor:
def __init__(self, text):
self.text = text
def count_words(self):
return len(self.text.split())
def reverse(self):
return self.text[::-1]
def to_title_case(self):
return self.text.title()
# 使用示例
processor = TextProcessor("python oop programming")
print(processor.count_words()) # 3
print(processor.reverse()) # gnimmargorp poo nohtyp
print(processor.to_title_case()) # Python Oop Programming
3. 字符串格式化(OOP风格)
class ReportGenerator:
def __init__(self, title, data):
self.title = title
self.data = data
def generate(self):
return f"""
Report: {self.title}
{'='*30}
Total Items: {len(self.data)}
Average: {sum(self.data)/len(self.data):.2f}
"""
# 使用示例
report = ReportGenerator("Sales Data", [45, 78, 92])
print(report.generate())
二、面向对象编程中的序列化
1. 序列化基础
序列化是将对象转换为可存储或传输格式的过程:
import pickle
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age})"
# 创建对象
p = Person("Alice", 30)
2. 使用Pickle序列化
class ObjectSerializer:
@staticmethod
def serialize_to_pickle(obj, filename):
with open(filename, 'wb') as f:
pickle.dump(obj, f)
@staticmethod
def deserialize_from_pickle(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
# 使用示例
ObjectSerializer.serialize_to_pickle(p, 'person.pkl')
loaded_p = ObjectSerializer.deserialize_from_pickle('person.pkl')
print(loaded_p) # Alice (30)
3. 使用JSON序列化
class JSONSerializer:
@staticmethod
def to_json(obj):
return json.dumps(obj.__dict__)
@staticmethod
def from_json(json_str, cls):
data = json.loads(json_str)
return cls(**data)
# 使用示例
json_str = JSONSerializer.to_json(p)
print(json_str) # {"name": "Alice", "age": 30}
new_p = JSONSerializer.from_json(json_str, Person)
print(new_p) # Alice (30)
4. 自定义序列化
class CustomSerializable:
def serialize(self):
return {
'class': self.__class__.__name__,
'data': self.__dict__
}
@classmethod
def deserialize(cls, data):
obj = cls.__new__(cls)
obj.__dict__.update(data['data'])
return obj
class Product(CustomSerializable):
def __init__(self, id, name, price):
self.id = id
self.name = name
self.price = price
# 使用示例
prod = Product(101, "Laptop", 999.99)
serialized = prod.serialize()
print(serialized)
new_prod = Product.deserialize(serialized)
print(new_prod.name) # Laptop
三、面向对象编程中的文件路径处理
1. 使用pathlib模块(OOP风格)
pathlib
提供了面向对象的文件系统路径操作:
from pathlib import Path
class FileManager:
def __init__(self, base_path):
self.base_path = Path(base_path)
def resolve_path(self, relative_path):
return self.base_path / relative_path
def read_file(self, relative_path):
full_path = self.resolve_path(relative_path)
return full_path.read_text()
def write_file(self, relative_path, content):
full_path = self.resolve_path(relative_path)
full_path.write_text(content)
return full_path.exists()
# 使用示例
manager = FileManager("/tmp")
print(manager.resolve_path("test.txt")) # /tmp/test.txt
manager.write_file("test.txt", "Hello OOP!")
print(manager.read_file("test.txt")) # Hello OOP!
2. 文件系统操作的封装
class DirectoryAnalyzer:
def __init__(self, directory):
self.dir_path = Path(directory)
def get_file_list(self, pattern="*"):
return list(self.dir_path.glob(pattern))
def get_file_sizes(self):
return {f.name: f.stat().st_size for f in self.dir_path.iterdir() if f.is_file()}
def find_largest_file(self):
files = self.get_file_list()
if not files:
return None
return max(files, key=lambda f: f.stat().st_size)
# 使用示例
analyzer = DirectoryAnalyzer(".")
print(analyzer.get_file_list("*.py"))
print(analyzer.get_file_sizes())
print(analyzer.find_largest_file())
3. 路径操作的实用类
class PathUtilities:
@staticmethod
def safe_join(base, *parts):
base_path = Path(base)
for part in parts:
base_path /= part
return base_path.resolve()
@staticmethod
def ensure_directory(path):
path = Path(path)
path.mkdir(parents=True, exist_ok=True)
return path
@classmethod
def create_temp_dir(cls, prefix="tmp_"):
import tempfile
temp_dir = Path(tempfile.mkdtemp(prefix=prefix))
return cls.ensure_directory(temp_dir)
# 使用示例
safe_path = PathUtilities.safe_join("/tmp", "..", "var", "log")
print(safe_path) # /var/log
temp_dir = PathUtilities.create_temp_dir("myapp_")
print(temp_dir) # /tmp/myapp_xxxxxx
四、综合应用示例
1. 配置文件管理器
import json
from pathlib import Path
class ConfigManager:
def __init__(self, config_path):
self.config_path = Path(config_path)
self._config = None
@property
def config(self):
if self._config is None:
self.load()
return self._config
def load(self):
if not self.config_path.exists():
self._config = {}
return
with open(self.config_path, 'r', encoding='utf-8') as f:
self._config = json.load(f)
def save(self):
with open(self.config_path, 'w', encoding='utf-8') as f:
json.dump(self.config, f, indent=2)
def get(self, key, default=None):
return self.config.get(key, default)
def set(self, key, value):
self.config[key] = value
self.save()
# 使用示例
config = ConfigManager("app_config.json")
config.set("language", "Python")
print(config.get("language")) # Python
2. 日志文件轮转器
from pathlib import Path
import time
import gzip
import shutil
class LogRotator:
def __init__(self, log_file, max_size=1024*1024, backup_count=5):
self.log_file = Path(log_file)
self.max_size = max_size
self.backup_count = backup_count
def needs_rotation(self):
return self.log_file.exists() and self.log_file.stat().st_size > self.max_size
def rotate(self):
if not self.needs_rotation():
return False
timestamp = int(time.time())
backup_file = self.log_file.with_name(f"{self.log_file.stem}_{timestamp}{self.log_file.suffix}.gz")
# 压缩当前日志文件
with open(self.log_file, 'rb') as f_in:
with gzip.open(backup_file, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# 清空原日志文件
self.log_file.write_text('')
# 清理旧的备份文件
self._cleanup_backups()
return True
def _cleanup_backups(self):
backups = sorted(self.log_file.parent.glob(f"{self.log_file.stem}_*{self.log_file.suffix}.gz"),
key=lambda f: f.stat().st_mtime, reverse=True)
for old_backup in backups[self.backup_count:]:
old_backup.unlink()
# 使用示例
rotator = LogRotator("app.log", max_size=100) # 设置为100字节便于测试
Path("app.log").write_text("This is a log message that exceeds the maximum size limit")
rotator.rotate()
五、最佳实践
-
字符串处理:
- 优先使用f-string进行字符串格式化
- 将常用字符串操作封装为类方法
- 考虑使用
__str__
和__repr__
方法增强对象可读性
-
序列化:
- 简单场景使用JSON,复杂对象使用Pickle
- 考虑实现自定义序列化协议以获得更好控制
- 注意序列化安全性问题(特别是Pickle)
-
文件路径:
- 优先使用
pathlib
而非os.path - 封装路径操作提高代码可读性和安全性
- 处理路径时考虑跨平台兼容性
- 优先使用
-
通用建议:
- 遵循单一职责原则,每个类专注一个功能
- 使用属性(@property)控制对文件/字符串状态的访问
- 考虑使用上下文管理器处理文件资源
全文总结
本文通过多个示例详细介绍了Python面向对象编程中的字符串处理、序列化和文件路径操作。在字符串处理部分,通过TextProcessor
和ReportGenerator
类展示了如何封装常用字符串操作和格式化方法。序列化部分则通过pickle
和json
模块,以及自定义序列化协议,展示了如何将对象转换为可存储或传输的格式。文件路径操作部分,使用pathlib
模块实现了面向对象的路径管理,并通过FileManager
和DirectoryAnalyzer
类封装了文件读写和目录分析功能。最后,通过配置文件管理和日志文件轮转器的综合应用示例,展示了如何将面向对象编程应用于实际问题。文章总结了面向对象编程的最佳实践,包括优先使用f-string、封装路径操作、考虑序列化安全性等,旨在帮助开发者提高代码的可读性、安全性和可维护性。