天天看点

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

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

by:授客 QQ:1033553122

代码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())

运行结果:

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

说明:

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

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

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

代码2

        pass

        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

print(obj.get_files_in_dirpath('E:\mygit\AutoTestPlatform/UIAutotest'))

运行结果:

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

作者:授客

QQ:1033553122

全国软件测试QQ交流群:7156436

Git地址:https://gitee.com/ishouke

友情提示:限于时间仓促,文中可能存在错误,欢迎指正、评论!

作者五行缺钱,如果觉得文章对您有帮助,请扫描下边的二维码打赏作者,金额随意,您的支持将是我继续创作的源动力,打赏后如有任何疑问,请联系我!!!

           微信打赏                       

支付宝打赏                  全国软件测试交流QQ群  

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