如何创建多对多关系变量并提高代码可用性?

时间:2019-01-01 21:30:33

标签: python

我正在尝试创建一个通用的实用程序,用于从源到目标的文件传输。自变量分为dirfilename,这分别是os.path.dirname(some_file)os.path.basename(some_file)的结果。如果未指定,默认情况下,目标文件名与源文件名相同。

我创建的脚本至少可以与我的第一个项目中的特定要求完美配合。但是,您可以注意到,get_src_des方法非常重复,我想从令人讨厌的if ... elif ...语句中提高代码的可重用性。有谁有更好的主意来重写此方法?

class FileTransfer:

    def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
        self.ftp_dir = ftp_dir
        self.ftp_filename = ftp_filename
        self.local_dir = local_dir
        self.local_filename = local_filename

        self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
        self.local_dict = self.get_group(local_dir, local_filename)

    @staticmethod
    def get_group(dir, filename):
        group = {
            "dir": dir,
            "filename": filename,
        }
        return group

    def get_src_des(self, src):
        if src == "ftp":
            dict_src = self.ftp_dict
            dict_des = self.local_dict
        elif src == "local":
            dict_src = self.local_dict
            dict_des = self.ftp_dict
        else:
            dict_src = None
            dict_des = None

        return dict_src, dict_des

    # other methods, such as download_from_src_to_des, upload_from_src_to_des, ...

2 个答案:

答案 0 :(得分:2)

是的。这是字典的经典用例。

您可以按以下方式重写代码:

class FileTransfer:

    def __init__(self, ftp_dir, local_dir, ftp_filename=None, local_filename=None):
        self.ftp_dir = ftp_dir
        self.ftp_filename = ftp_filename
        self.local_dir = local_dir
        self.local_filename = local_filename

        self.ftp_dict = self.get_group(ftp_dir, ftp_filename)
        self.local_dict = self.get_group(local_dir, local_filename)
        self.param_dict = {
            'ftp':(self.ftp_dict,self.local_dict),
            'local' : (self.local_dict,self.ftp_dict)
        }

    @staticmethod
    def get_group(dir, filename):
        group = {
            "dir": dir,
            "filename": filename,
        }
        return group

    def get_src_des(self, src):
        if src in param_dict:
           return param_dict[src]

        else:
          return (None,None)

下次,您无需添加其他elif语句,而只需在param_dict

中添加另一个条目

答案 1 :(得分:1)

我同意可以使用字典来完成,正如@Yakov Dan的答案所建议的那样,但是我将按如下所示对其进行编码,它不需要对class进行任何其他更改,并且更加动态。

如所示,可以更简洁地编写get_group()方法。

class FileTransfer:
    ...

    @staticmethod
    def get_group(dir, filename):
        return dict(dir=dir, filename=filename)

    def get_src_des(self, src):
        return {
            'ftp': (self.ftp_dict, self.local_dict),
            'local': (self.local_dict, self.ftp_dict)
        }.get(src, (None, None))