Reputation: 119
I want to create two very similar methods in class.
The only diffrence in methods is a way of adding element to a list
, other code stays the same.
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
Is there any cleaner way than copy paste code?
Upvotes: 0
Views: 80
Reputation: 4452
I don't know how your exact code looks like but you could do something like:
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
or
class Test:
a = []
def test(self, option):
codetoexecute
if (option):
self.a.append('test1')
else:
self.insert(0, 'test2')
Edit
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
Upvotes: 1
Reputation: 366
Make a method in the class for all the logic without inserting in the list. Name it with a leading underscore, as it should be considered private.
def _process (self):
...
...
Then:
def test1(self):
self._process()
self.a.append('test1')
def test2(self):
self._process()
self.insert(0, 'test2')
If you need to do things before and after the insertion, make two new methods.
Upvotes: 0