TMikonos
TMikonos

Reputation: 369

Python - Inheritance of a composition class

I have 2 classes that are a composition. And I would need to extend the functionality of both, so I would need to make use of inheritance from those base classes. Is it possible?

class Book:
    def __init__(self):
        self.sheets = generate_sheets()
    author = ''

    def generate_sheets(self):
         for index in range(20):
             (some_extra code)
             self.sheets.append(Sheet(index))

class Sheet:
    def __init__(self, idx):
        self.id = idx

And I want to create 2 children of the base, and that the composition be between them. It would only possible overwriting the method generate_sheets?

class DefinitionBook(Book):
    def __init__(self):
        super().__init__()
    translator = ''

    def generate_sheets(self):
        super().__init__()
        for index in range(20):
            self.sheets.append(DefSheet(index)

class DefSheet(Sheet):
    def __init__
        super().__init__()
    definition = dict()

Or it would be possible to keep part of the code of the method generate_sheets in the child class of Book, and only change the part where is called to the class Sheet/DefSheet?

Upvotes: 1

Views: 91

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36682

You could have the class Sheet (and subclasses) you need to use, as a class variable in the class Book (and subclasses); this voids the need to override generate_sheets in the subclasses.

class Sheet:
    def __init__(self, idx):
        self.id = idx
    def __str__(self):
        return f"{self.__class__.__name__}"

class Book:
    sheet = Sheet    
    def __init__(self):
        self.sheets = []
        self.generate_sheets()

    def generate_sheets(self):
        for index in range(20):
            self.sheets.append(self.__class__.sheet(index))

    def __str__(self):
        return f"{self.__class__.__name__} - {self.sheet.__name__}"



class DefSheet(Sheet):
    def __init__(self, idx):
        super().__init__(idx)

class DefinitionBook(Book):
    sheet = DefSheet
    def __init__(self):
        super().__init__()


b = Book()
print(b, b.sheets[0])
d = DefinitionBook()
print(d, d.sheets[0])

output:

Book - Sheet Sheet
DefinitionBook - DefSheet DefSheet

Upvotes: 4

Related Questions