如何在Python的init函数中消除代码重复

3

我刚开始学习编程。我在一个类中创建了以下函数。我注意到我正在重复我的代码。我正在寻找最佳解决方案来消除这种重复。

我在我的类中有以下函数:

def init(self):
    if not os.path.exists(self.src_flag):
        if os.path.exists(self.src):
            removeFolder(self.src)
        print 'File {0} does not exist'.format(self.src_flag)
        open(self.src_flag, 'a').close()

    if not os.path.exists(self.dst_flag):
        if os.path.exists(self.dst):
            removeFolder(self.dst)
        print 'File {0} does not exist'.format(self.dst_flag)
        open(self.dst_flag, 'a').close()

然后我通过调用这个函数来实现

Folder.init()

不确定这是否是最佳方案,但我考虑将函数更改为以下内容:

def init(self, flag, path):
    if not os.path.exists(flag):
        if os.path.exists(path):
            removeFolder(path)
        print 'File {0} does not exist'.format(flag)
        open(flag, 'a').close()

但是我必须运行两次函数才能执行它的src和dst,例如:

Folder.init('C:\src\flag.txt', 'C:\src')
Folder.init('C:\dst\flag.txt', 'C:\dst')

有人能告诉我我的解决方案是否可行,或者是否有更好的方法吗?

2个回答

1
当您执行完全相同的代码块时,显然应该使用循环。唯一的问题是如何获取参数,您可以通过几种方式来完成,并选择最适合您的方式:
  1. Just pass 2 lists: one for the paths and one for the corresponding flags. Now you can iterate over them using zip:

    def init(self, flags, paths):
        for flag, path in zip(flags, paths):
            # your block with flag and path
    

    You would call it like:

    Folder.init(['C:\src\flag.txt', 'C:\dst\flag.txt'], ['C:\src', 'C:\dst'])

  2. Alternatively, pass a list of already paired flags and paths:

    def init(self, pairs):
        for flag, path in pairs:
            # your block with flag and path
    

    You would call it like:

    Folder.init([('C:\src\flag.txt', 'C:\src'), ('C:\dst\flag.txt', 'C:\dst')])

  3. Just pass all arguments together, assuming they are ordered in pairs. Then, iterate on pairs:

    def init(self, *args):
        for i in range(0, len(args)-1, 2):
            flag = args[i]
            path = args[i+1]
            # your block with flag and path
    

    Or, using zip again:

    for flag, path in zip(args[::2], args[1::2]):
        # your block with flag and path
    

    You would call it like: Folder.init('C:\src\flag.txt', 'C:\src', 'C:\dst\flag.txt', 'C:\dst')

  4. Lastly, you didn't mention that in the question, but assuming path is the directory of the file flag, you can use the os.path module and just pass the flags and get path using the dirname function:

    def init(self, *flags):
        for flag in flags:
            path = os.path.dirname(flag)
            # your block with flag and path
    

    You would call it like: Folder.init('C:\src\flag.txt', 'C:\dst\flag.txt')


0

你可以将数组作为参数,并在函数中循环遍历[src,dst]数组。因此,您可以在方法中构建路径,并仅在路径中交换src / dst部分。

只有当src和dest始终一起初始化时,这才有意义。如果您在一个单独的方法调用中使用完整路径,则可以摆脱2个类似的方法调用或4个参数。

如果不是这种情况,我喜欢您的解决方案和两个调用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接