处理资源路径的正确方法是什么?

问题描述 投票:0回答:1

我正在使用 Python,我的多个 GUI 类需要一些图像。

是否可以简单地通过常量添加资源路径并将其导入到各处?
我正在考虑的另一种方法是为每个对象创建设置器并在初始化应用程序时使用它们。但我觉得这会造成不必要的复杂性。

这些有效吗,还有其他方法吗?

python python-3.x tkinter
1个回答
0
投票

Python 有一些有效的资源管理实现:

常量:最适合小型项目或数据路径不太可能改变的情况。

Setters:当需要在运行时自定义路径时很有用。

配置文件:适合数据量大的大型项目,方便管理。

# config.yaml
image_path: "path/to/image.png"

# config.py
import yaml

def load_config():
    with open("config.yaml", "r") as file:
        return yaml.safe_load(file)

config = load_config()

# gui_class.py
from config import config
from PIL import Image

class MyGUIClass:
    def __init__(self):
        self.image_path = config['image_path']
        self.load_image(self.image_path)
    
    def load_image(self, path):
        self.image = Image.open(path)

资源管理类:最适合封装数据逻辑并提供复用。

class ResourceManager:
    def __init__(self, config):
        self.config = config
    
    def get_image(self, image_name):
        return Image.open(self.config[image_name])

结论:

以一种使资源路径易于更新和维护的方式构建代码非常重要。

选择最适合您项目的规模、复杂性和灵活性的方法。对于许多应用程序,最好的变体可能是从常量配置文件开始,然后根据需要转向更复杂的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.