我患了“类太多”综合症,很难确定什么时候在python中使用类是合理的。你知道吗
我有一个函数,它的代码很快升级到大约350行代码,为了有全面的测试和对代码本身的更多控制,重构突然出现在我的脑海中。你知道吗
刚开始重构,我就把代码分成几个小函数,但它们依赖于一些变量和数据字典,现在必须作为参数传递。你知道吗
原始代码如下所示:
def process_rooms_json(path, country, json_dict):
# Create Dict from json_dict
rooms_dict = dict()
# Create another
employee_dict = dict()
list_meetings = []
# Iterate over the folder
for file_name in [f for f in os.listdir(path)]:
with open(folder + '/' + file_name, 'r', encoding='utf-8') as f:
# Extract contect
set_apps = function_which_creates_list(f.read())
for app in set_apps:
# Block of code which extracts certain info
# Block of code which build a dictionary
list_meetings.append(result_of_big_code)
return list_meetings
现在它就像
def process_rooms_json(path, country, json_dict):
# Create Dict from json_dict
rooms_dict = dict()
# Create another
employee_dict = dict()
list_meetings = []
# Iterate over the folder
for file_name in [f for f in os.listdir(path)]:
with open(folder + '/' + file_name, 'r', encoding='utf-8') as f:
# Extract content
set_apps = function_which_creates_list(f.read())
for app in set_apps:
# Block of code which extracts certain info
new_dict = do_a_lot_of_stuff_1(employee_dict, country, filename)
new_dict2 = do_a_lot_of_stuff_2(new_dict['some_list'])
new_dict3 = do_a_lot_of_stuff_3(employee_dict, country)
new_dict4 = do_a_lot_of_stuff_4(rooms_dict, country, file_name)
new_dict5 = do_a_lot_of_stuff_5(rooms_dict, employee_dict)
# Create result
return_dict = dict()
return_dict['some_filed'] = new_dict['another field']
...
list_meetings.append(return_didct)
return list_meetings
我真的很想创建一个类,比如RoomProcessor,并将路径、json字典和国家代码封装在self中。我不知道这在多大程度上是正确的,或者我是否完全失去了重点。你知道吗
在可维护性、代码可读性和适当的python惯用方法方面,跨“函数”共享相同的数据字典是否有适当的理由来创建类?你知道吗
目前没有回答
相关问题 更多 >
编程相关推荐