首页 > 解决方案 > 使用 OOP 时如何避免代码重复

问题描述

下面的代码定义了一个AppConfig类:

import os 
import json 

class AppConfig(object):

    def read_config(self, name):        
        filepath = os.path.expanduser("~/%s.cfg" % name)

        if os.path.exists(filepath):
            with open(filepath, 'rb') as file:
                return json.loads(file.read())

        else:
            return dict()

    def write_config(self, name, data):
        filepath = os.path.expanduser("~/%s.cfg" % name)

        with open(filepath, 'w') as file:
            json.dump(data, file)

    def update_config(self, name, key, value):
        filepath = os.path.expanduser("~/%s.cfg" % name)

        data = self.read_config(name)
        data[key] = value

        with open(filepath, 'w') as file:
            json.dump(data, file)

它具有三种方法read_configwrite_configupdate_config。所有三种方法都将路径组装到配置文件路径:

filepath = os.path.expanduser("~/%s.cfg" % name)

这里显然有代码重复。如何编辑此代码以使其更清晰、更易于阅读以避免代码重复?还可以做些什么来使它更 Pythonic?

请随意使用下面的代码来玩这个类:

appConf = AppConfig()

data = {1: "one", 2: "two"}
appConf.write_config("my-app", data)

data = {3: "one", 4: "two"}
appConf.update_config(name = "my-app",  key = 3, value = "three")

conf = appConf.read_config("my-app")
print(conf) 

标签: python

解决方案


利用__init__

import os
import json

class AppConfig(object):
    def __init__(self,name):
        self.filepath = os.path.expanduser("~/%s.cfg" % name)

    def read_config(self):
        if os.path.exists(self.filepath):
            with open(self.filepath, 'rb') as file:
                return json.loads(file.read())

        else:
            return dict()

    def write_config(self, data):
        with open(self.filepath, 'w') as file:
            json.dump(data, file)

    def update_config(self, key, value):
        data = self.read_config()
        data[key] = value
        self.write_config(data)

您的类维护的状态是给定用户的配置文件的路径。该状态应存储在实例属性中,在创建对象时初始化。后面的方法调用访问self.filepath而不是每个都name作为参数并重复重建路径。


推荐阅读