1

In this minimum working example, Classes A and B do the same thing but their methods are slightly different. They save an item to their respective lists and display them. However, I would like to define an abstract Save class which refactors a lot of the repeated code here. Is there a way to do this?

class A():
  def __init__(self):
    self.items = []

  def save(self, item):
    item = "This is {}".format(item)
    self.items.append(item)
      
  def display(self):
    return self.items


class B():
  def __init__(self):
    self.items = []

  def save(self, item):
    item = "This is {}...!".format(item)
    self.items.append(item)
      
  def display(self):
    return self.items

a = A()
a.save('A')
a.save('B')
print(a.display())

b = B()
b.save('C')
b.save('D')
print(b.display())

Output

['This is A', 'This is B']
['This is C...!', 'This is D...!']
1
  • 1
    what are you trying to accomplish this this? Commented Oct 28, 2020 at 1:00

1 Answer 1

2
class Save:
    def __init__(self):
        self.items = []

    def save(self, item):
        item = self.format_item(item)
        self.items.append(item)

    def display(self):
        return self.items

class A(Save):
    def format_item(self, item):
        return 'This is {}'.format(item)

class B(Save):
    def format_item(self, item):
        return 'This is {}...!'.format(item)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.