OOP:两种非常相似的方法,但不同类型的数据 - 如何优化?

时间:2017-06-08 06:20:47

标签: python-3.x oop methods

我试图优化一些代码。具体来说,我有两种方法在他们的工作方面非常相似。它们执行的操作是相同的,区别在于一个连接字符串,另一个将这些字符串附加到列表中。不同方法的唯一部分是涉及字符串或特定于列表的方法/操作的实例。

示例:

    class Some_Class:
        def __init__(self, num): 
            self.num = num 

        def some_function(self): 
            collector = ''
            for x in range(self.num):
                #do something
                collector+= #the something
            return collector

        def some_function(self): 
            collector = []
            for x in range(self.num):
                #do something
                collector.append(#the result of something)
            return collector

优化代码的最佳方法是什么?一个简单的

    if type(data) == str:
        #do something
    else:
        #assume it's a list, and act accordingly

...导致难看的,难以听到的代码,因为我必须在多个地方写这个。建议?

1 个答案:

答案 0 :(得分:1)

我可能会误解你的想法,但无论如何这里有一些建议。

如果您说的两种方法相似,基本上做同样的事情,但产生不同的格式化响应,您可以做的就是如下所示将重复的代码合并到类的单个私有函数中:

class Some_Class:
    def __init__(self, num): 
        self.num = num 

    # obviously these two `some_function`s wouldn't have the same name?
    def some_function(self): 
        collector = ''
        for x in range(self.num):
            result = self._do_something(<some args>)
            collector+= result
        return collector

    def some_function(self): 
        collector = []
        for x in range(self.num):
            result = self._do_something(<some args>)
            collector.append(result)
        return collector

    def _do_something(self, <some args>):
        # common function containing all the repeated functionality
        # between the other two functions

        # do something

如果你必须在一个函数中拥有所有东西,那么你的if / else示例可能仍然是一个很好的方法。也许使用bool变量而不是每次调用type都会更整洁。