有一段代码可以将文件中的设置重置YAML为最初安装程序时的设置。但现在代码只能重置一个类,而增加数量的问题是我不知道如何利用ООПpython 的功能来紧凑地完成它。如何实施?
设置.py:
from abc import ABC, abstractmethod
from dataclasses import dataclass
from pathlib import Path
from enum import Enum
import yaml
from src.settings.default_settings import JetInjectorConstant, CentrifugalInjectorConstant
class ListNameSettingsFile(Enum):
"""
РУС: Список файлов конфигурации
ENG: List of configuration files
"""
LIST_NAME_SETTINGS_FILE = ["injector_settings"]
@dataclass(frozen=True)
class Settings(ABC):
"""
РУС: Основной класс для обработки файлов конфигурации
ENG: The main class for processing configuration files
"""
@staticmethod
def get_root_dir():
"""
РУС: Директория установки ПО
ENG: The software installation directory
"""
return Path(__file__).absolute().parent
@abstractmethod
def get_data_for_recording(self) -> dict:
"""
РУС: Получение данных для загрузки в файл конфигурации
ENG: Getting data to upload to a configuration file
"""
raise NotImplementedError("Данные настроек не загружены")
@abstractmethod
def name_settings_file(self) -> str:
"""
РУС: Получение имени файла конфигурации
ENG: Getting the name of the configuration file
"""
raise NotImplementedError("Имя файла настроек не загружено")
@property
def save_settings(self) -> None:
"""
РУС: Запись констант в файл конфигурации
ENG: Writing constants to a configuration file
"""
with open((self.get_root_dir() / "data").joinpath(self.name_settings_file() + ".yaml"), "w") as outfile:
new_dump = yaml.dump(self.get_data_for_recording())
outfile.write(new_dump)
return None
@property
def read_settings(self) -> dict | None:
"""
РУС: Чтение констант из файла конфигурации
ENG: Reading constants from a configuration file
"""
try:
with open((self.get_root_dir() / "data").joinpath(self.name_settings_file() + ".yaml"), "r") as stream:
read_date = yaml.safe_load(stream)
return read_date
except FileNotFoundError:
return InjectorSettings.reset_to_default()
@dataclass(frozen=True)
class InjectorSettings(Settings):
"""
РУС: Класс констант для проведения расчетов
ENG: A class of constants for performing calculations
"""
laminar: float | None = None
turbulent: float | None = None
right_angle: float | None = None
def get_data_for_recording(self) -> dict:
"""
РУС: Загрузка констант для расчетов
ENG: Loading constants for calculations
"""
injector_settings = {
"reynolds": {"laminar": self.laminar, "turbulent": self.turbulent},
"right_angle": self.right_angle,
}
return injector_settings
def name_settings_file(self) -> str:
"""
РУС: Передача имени файла конфигурации
ENG: Passing the name of the configuration file
"""
return ListNameSettingsFile.LIST_NAME_SETTINGS_FILE.value[0]
@staticmethod
def reset_to_default() -> None:
"""
РУС: Восстановление значений по умолчанию и запись их в файл конфигурации
ENG: Resetting to default values and saving them to the configuration file
"""
default_settings = InjectorSettings(
laminar=JetInjectorConstant.LAMINAR.value,
turbulent=JetInjectorConstant.TURBULENT.value,
right_angle=CentrifugalInjectorConstant.RIGHT_ANGLE.value
)
return default_settings.save_settings
默认设置.py:
from enum import Enum
class JetInjectorConstant(Enum):
"""Стандартные значение констант струйной """
LAMINAR = 2000
TURBULENT = 10_000
class CentrifugalInjectorConstant(Enum):
"""Стандартные значение констант центробежной форсунки"""
RIGHT_ANGLE = 90
代码说明:我们有一个主类Settings,其中包含读写文件的函数,还有一个类InjectorSettings,包含与加载计算数据相关的操作。但是,假设我们要添加另一个类,那么我们用于重置设置的代码将不起作用,因为在异常Settings函数的类中没有错误文件的定义。read_settings