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:\mygit\AutoTestPlatform/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:\mygit\AutoTestPlatform/UIAutotest'))

 

运行结果:

 

posted @ 2018-01-14 11:28  授客  阅读(255)  评论(0编辑  收藏  举报