關于類函數設計的一點總結
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())
運作結果:

說明:
如上,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'))
運作結果:
作者:授客
QQ:1033553122
全國軟體測試QQ交流群:7156436
Git位址:https://gitee.com/ishouke
友情提示:限于時間倉促,文中可能存在錯誤,歡迎指正、評論!
作者五行缺錢,如果覺得文章對您有幫助,請掃描下邊的二維碼打賞作者,金額随意,您的支援将是我繼續創作的源動力,打賞後如有任何疑問,請聯系我!!!
微信打賞
支付寶打賞 全國軟體測試交流QQ群