zoukankan      html  css  js  c++  java
  • Python 关于类函数设计的一点总结

    关于类函数设计的一点总结

    by:授客 QQ1033553122

    代码1

    #!/usr/bin/env python

    #-*-encoding:utf-8-*-

     

    __author__ = 'shouke'

     

    import os

     

    class MyTestClass:

        def __init__(self):

            self.file_list_for_dirpath = []

     

        # 获取指定目录下的文件

        def get_files_in_dirpath(self, dirpath):

            if not os.path.exists(dirpath):

                print('路径:%s不存在,退出程序' % dirpath)

                exit()

     

            for name in os.listdir(dirpath):

                full_path = os.path.join(dirpath, name)

                if os.path.isdir(full_path):

                    self.get_files_in_dirpath(full_path)

                else:

                    self.file_list_for_dirpath.append(full_path)

     

        def get_file_list_for_dirpath(self):

            return self.file_list_for_dirpath

     

    obj  = MyTestClass()

    obj.get_files_in_dirpath('E:mygitAutoTestPlatform/UIAutotest')

    print(obj.get_file_list_for_dirpath())

     

    运行结果:

    说明:

    如上,get_files_in_dirpath函数目的是为了获取指定目录下的文件,按常理是函数中定义个变量,存放结果,最后直接return这个变量就可以了,但是因为涉及子目录的遍历,函数中通过self.get_files_in_dirpath对函数进行再次调用,这样一来,便无法通过简单的return方式返回结果了。

     

    个人觉得比较不合理的方式就是按上面的,“强行”在类中定义个类属性来存放这个结果,然后再定义个函数,返回这个结果,感觉这样设计不太好,还会增加代码逻辑的模糊度。

     

    那咋办?个人觉得比较合理的解决方案,可以使用嵌套函数。如下:

     

    代码2

    #!/usr/bin/env python

    #-*-encoding:utf-8-*-

     

    __author__ = 'shouke'

     

    import os

     

    class MyTestClass:

        def __init__(self):

            pass

     

        # 获取指定目录下的文件

        def get_files_in_dirpath(self, dirpath):

            file_list_for_dirpath = []

            def collect_files_in_dirpath(dirpath):

                nonlocal file_list_for_dirpath

                if not os.path.exists(dirpath):

                    print('路径:%s不存在,退出程序' % dirpath)

                    exit()

     

                for name in os.listdir(dirpath):

                    full_path = os.path.join(dirpath, name)

                    if os.path.isdir(full_path):

                        collect_files_in_dirpath(full_path)

                    else:

                        file_list_for_dirpath.append(full_path)

     

            collect_files_in_dirpath(dirpath)

            return file_list_for_dirpath

     

    obj  = MyTestClass()

    print(obj.get_files_in_dirpath('E:mygitAutoTestPlatform/UIAutotest'))

     

    运行结果:

  • 相关阅读:
    C++编写ATM(2)
    【Python排序搜索基本算法】之Dijkstra算法
    Java中List转换为数组,数组转List
    [置顶] 亚信联创实习笔记
    PL/SQL 异常处理程序
    CSS position财产
    malloc()与calloc差异
    Qt5官方demo分析集10——Qt Quick Particles Examples
    栈和堆之间的差
    深入浅出JMS(一)——JMS简要
  • 原文地址:https://www.cnblogs.com/shouke/p/10157526.html
Copyright © 2011-2022 走看看