课堂上类似的方法

时间:2018-11-08 19:02:07

标签: python methods

我想在课堂上创建两个非常相似的方法。

方法的唯一区别是向list添加元素的方式,其他代码保持不变。

class Test:
    a = []
    def test1(self):
        ...
        self.a.append('test1')
        ...

    def test2(self):
        ...
        self.insert(0, 'test2')
        ...

    def compute(self):
        while not self.is_answer:
            node = self.visited[0]
            for operator in self.order:
                next_node = node.next_node(operator)
                if (next_node and next_node not in self.computed
                        and next_node not in self.visited):
                    if next_node.check_answer():
                        self.is_answer = True
                        print('Answer found')
                        break
                    else:
                        self.visited.insert(0, next_node) <--- here I want change methods
            self.computed.append(self.visited.pop(0))
            self.depth += 1

除了复制粘贴代码外,还有什么更干净的方法吗?

2 个答案:

答案 0 :(得分:1)

我不知道您的确切代码是什么样子,但是您可以执行以下操作:

class Test:
   a = []
   def test1(self):
       self._similar_code()
       self.a.append('test1')

   def test2(self):
       self._similar_code()
       self.insert(0, 'test2')

   def _similar_code(self):
       pass

class Test:
   a = []
   def test(self, option):
       codetoexecute
       if (option):
           self.a.append('test1')
       else:
           self.insert(0, 'test2')

修改

def compute(self, option):
    while not self.is_answer:
        node = self.visited[0]
        for operator in self.order:
            next_node = node.next_node(operator)
            if next_node and next_node not in self.computed and next_node not in self.visited:
                if next_node.check_answer():
                    self.is_answer = True
                    print('Answer found')
                    break
                else:
                    if (option):
                        self.visited.insert(0, next_node)
                    else:
                        self.visited.append(next_node)
        self.computed.append(self.visited.pop(0))
        self.depth += 1

答案 1 :(得分:0)

在类中为所有逻辑创建一个方法,而无需插入列表。用下划线将其命名,因为它应被视为私有。

def _process (self):
    ...
    ...

然后:

def test1(self):
    self._process()
    self.a.append('test1')

def test2(self):
    self._process()
    self.insert(0, 'test2')

如果您需要在插入前后进行操作,请使用两种新方法。