Last active
December 27, 2018 04:37
-
-
Save rdcoder33/eba600d23fafd9c477533e72271158ec to your computer and use it in GitHub Desktop.
Example of Composition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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