[英]Python snippet refactoring
I got some little code snippet and i think about refactoring. 我有一些代码片段,我考虑了重构。 I really don't like it in part of
sort_paths_by_date
method beacuse of DRY principle and code clarity: 由于DRY原理和代码清晰,我真的不喜欢
sort_paths_by_date
方法的一部分:
from os.path import getctime, getmtime
class Endpoint(object):
def __init__(self, define_path_by, paths):
self.define_path_by = define_path_by
self.paths = paths
def sort_paths_by_date(self):
if self.define_path_by == 'ctime':
self.paths = sorted(
self.paths,
key=lambda cur_path: getctime(cur_path.path),
)
elif self.define_path_by == 'mtime':
self.paths = sorted(
self.paths,
key=lambda cur_path: getmtime(cur_path.path),
)
and i make it like this: 而我做到这样:
from os.path import getctime, getmtime
class Endpoint(object):
def __init__(self, define_path_by, paths):
self.define_path_by = define_path_by
self.paths = paths
def sort_paths_by_date(self):
def sort_with_func(func):
return sorted(
self.paths,
key=lambda cur_path: func(cur_path.path)
)
if self.define_date_by == 'ctime':
self.paths = sort_with_func(getctime)
elif self.define_date_by == 'mtime':
self.paths = sort_with_func(getmtime)
But now i'm not sure about function definition in method and again code clarity is confused me. 但是现在我不确定方法中的函数定义,并且代码的清晰度再次使我感到困惑。 So i will be appreciative for your refactoring experience here.
因此,对于您在这里的重构经验,我将不胜感激。
Your function does seem a little unnecessarily complicated. 您的功能似乎确实有些不必要的复杂。 It could simply be this:
可能只是这样:
def sort_paths_by_date(self):
if self.define_path_by in ('ctime', 'mtime'):
fn = getctime if self.define_path='ctime' else getmtime
self.paths = sorted(self.paths, key=lambda cur_path: fn(cur_path.path))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.