python - 当唯一改变的是方法时重构 Python 代码?
问题描述
需要一些关于如何重构这种代码的建议,正如你所看到的,所有的基本代码,左,右都是一样的,所有改变的是 .strip(), .lstrip(), .rstrip(),是否有可能以“美丽”的方式重构它?
def clean_whitespaces(input, mode='all', ):
result = None
modes = (None, 'all', 'left', 'right')
if mode not in modes:
raise ValueError('clean_whitespaces: mode must be one of {}.'.format(modes))
if mode == None:
mode = 'all'
if mode == 'all':
if isinstance(input, str):
result = input.strip()
else:
input = list(input)
result = [entry.strip() for entry in input]
return result
elif mode == 'left':
if isinstance(input, str):
result = input.lstrip()
else:
input = list(input)
result = [entry.lstrip() for entry in input]
return result
elif mode == 'right':
if isinstance(input, str):
result = input.rstrip()
else:
input = list(input)
result = [entry.rstrip() for entry in input]
return result
解决方案
您可以为此使用字典:
modes_to_func = {'all': str.strip, 'left': str.lstrip, 'right': str.rstrip}
这样,您可以避免迭代modes
:
def clean_whitespaces(input, mode='all', ):
modes = (None, 'all', 'left', 'right')
modes_to_func = {'all': str.strip, 'left': str.lstrip, 'right': str.rstrip}
if mode not in modes:
raise ValueError('clean_whitespaces: mode must be one of {}.'.format(modes))
if mode is None:
mode = 'all'
if isinstance(input, str):
result = modes_to_func[mode](input)
else:
input = list(input)
result = [modes_to_func[mode](entry) for entry in input]
return result
推荐阅读
- android - putExtraData 在 Kotlin Intent 中做了什么?
- mysql - yii中没有主键的关系mysql表搜索(调用非整数字段)
- javascript - asp.net网格的javascript行数据比较
- eclipse - xsl 输出 eclipse 中的额外命名空间
- javascript - 无法为 ng-select 分配旧值?
- php - wpforms:如何在自定义智能标签中查询表单描述?
- c++ - C ++中的ZigZag二叉树遍历
- vue.js - Axios-一次发出多个请求(vue.js)
- mysql - Mysql Master-Slave Replication Grant 权限解决错误
- javascript - 如何将 $location 设置为 $location.host