前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 关于类函数设计的一点总结

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

作者头像
授客
发布2019-09-10 18:49:01
3110
发布2019-09-10 18:49:01
举报
文章被收录于专栏:授客的专栏授客的专栏

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

运行结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-01-14 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 代码1
  • 代码2
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档