新手问题 - 将功能分解为两个

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

所以我是python的新手,我有一个功能,我需要分成两部分。以前这是一个功能,但经过一些比我更了解的人的建议,我得到了我的功能做得太多的提示,我需要把它分解为两个不同的东西;所以我在这里。

以下是分为两部分的代码。

我想知道我是否必须在两个功能中提及pathlist

这应该做的是检查文件是否存在然后如果它们运行第二个函数以删除实际目录。

def check_directory(pathslist):
    for path in pathslist:
        if os.path.exists(path) and os.path.isdir(path):
            remove_directory(pathslist)

dirs_to_delete = [
    'C:\MyDirectoryPath1',
    'C:\MyDirectoryPath2',
    'C:\MyDirectoryPath3'

 ]

def remove_directory(pathslist):
    for path in pathslist:
        if os.path.exists(path) and os.path.isdir(path):
            shutil.rmtree(path)
            print(colored('Found ' + path + ' removing', 'green'))
python python-3.x
1个回答
3
投票

不完全是。如果您将整个路径列表传递给remove_directory,那么无论是否存在,您都将尝试删除每个路径列表,从而无需使用check_directory函数。我认为你的意思是你的check_directory函数只传递remove_directory中存在的路径:

def check_directory(pathslist):
    for path in pathslist:
        if os.path.exists(path) and os.path.isdir(path):
            remove_directory(path)

dirs_to_delete = [
    'C:\MyDirectoryPath1',
    'C:\MyDirectoryPath2',
    'C:\MyDirectoryPath3'

 ]


def remove_directory(path):
     shutil.rmtree(path)
     print(colored('Found ' + path + ' removing', 'green'))

您可能想尝试为您编写的每个函数编写注释,描述它的作用。第二个你使用单词“和”或一个额外的动词,这是一个提示,你可能最好将功能分成多个部分(这只是一个经验法则,而不是绝对的)。此外,您希望避免重复代码 - 如果您在两个单独的函数中使用相同的代码行,那么您需要重新考虑设计的另一个提示。

编辑:正如评论中所指出的,你编写它的方式意味着调用check_directory将删除目录(如果存在)。似乎有理由期望有人会因为除了想要移除它之外的原因而调用check_directory,并且你最好让remove_directory调用check_directory而不是相反:

    def check_directory(path):
         # returns true if path is an existing directory
         return os.path.exists(path) and os.path.isdir(path)

    def remove_directory(pathlist):
        for path in pathlist:
            if check_directory(path):
                shutil.rmtree(path)
                print(colored('Found ' + path + ' removing', 'green'))

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