【问题标题】:OOP: two very similar methods, but different types of data --howto optimise?OOP:两种非常相似的方法,但数据类型不同——如何优化?
【发布时间】:2017-11-09 17:10:53
【问题描述】:

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

示例:

    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

...导致难看、难听的代码,因为我必须在多个地方编写它。推荐?

【问题讨论】:

  • 没有解释的否决票?真正的优雅。
  • 您已将您的方法称为同名,因此解释器只会找到一个。
  • 另一方面,您可以使用list 方法,当您知道它位于要连接的字符串值上时,请使用''.join(list_result)

标签: python-3.x oop methods


【解决方案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 会更整洁。

【讨论】:

  • 我希望有一些时髦的方法可以解决我的问题,但感谢您的意见! :)
猜你喜欢
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多