Python 片段重构

Python snippet refactoring

我得到了一些小代码片段,我正在考虑重构。由于 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),
            )

我是这样的:

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)

但现在我不确定方法中的函数定义,代码清晰度再次让我感到困惑。因此,我将感谢您在这里的重构经验。

你的函数看起来确实有点复杂。可能只是这样:

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))