简体   繁体   中英

How do I refactor different classes with the same methods in Python?

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...!']
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM