为了账号安全,请及时绑定邮箱和手机立即绑定

新手问题 - 将函数一分为二

新手问题 - 将函数一分为二

扬帆大鱼 2021-11-30 17:00:29
所以我是 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'))
查看完整描述

1 回答

?
心有法竹

TA贡献1866条经验 获得超5个赞

不完全是。如果您将整个路径列表传递给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'))

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


编辑:正如评论中所指出的,您编写它的方式意味着调用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'))


查看完整回答
反对 回复 2021-11-30
  • 1 回答
  • 0 关注
  • 172 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信