Skip to content

Instantly share code, notes, and snippets.

@rdcoder33
Last active December 27, 2018 04:37
Show Gist options
  • Save rdcoder33/eba600d23fafd9c477533e72271158ec to your computer and use it in GitHub Desktop.
Save rdcoder33/eba600d23fafd9c477533e72271158ec to your computer and use it in GitHub Desktop.
Example of Composition
class Book:
def __init__(self, name, author, publisher):
self.name = name
self.author = author
self.publisher = publisher
def book_details(self):
return f'{self.name} by {self.author} from {self.publisher}'
class Chapter:
def __init__(self, title, chap_num, name, author, publisher):
self.title = title
self.chap_num = chap_num
# using composition
self.book_obj = Book(name, author, publisher)
def chapter_details(self):
return f'Chapter {self.chap_num}: {self.title}, is taken from {self.book_obj.book_details()}'
# Chapter obj:
first_chap = Chapter('Composition', 1, 'Best Book', 'RD', 'RD-pubs')
print(first_chap.chapter_details())
# accessing class Book properties and methods using Chapter Class object
print(first_chap.book_obj.author)
print(first_chap.book_obj.book_details())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment