I am working in Python 3.6 and have two classes, one class serves as a container for a list of the other, but the nested class does not inherit from the higher-order class. Basically here is a simplification of what I'm looking at:
class Library():
def __init__(self, name, bookList):
"""
Initializes a library class object
Send: self (Library object), name (str), list of books in the library (list of Book objects)
"""
self.name=name
self.bookList=bookList
class Book():
def __init__(self, title, author, year):
"""
Initializes a book class object
Send: self (Book object), title (str), author (str), year (int)
"""
self.title=title
self.author=author
self.year=year
def owningLibrary(self):
"""
Identifies the name of the library that owns the book
Send: self (Book object)
"""
#some code that looks at the library's name and returns it
if __name__=="__main__":
#Create book
warAndPeace = Book("War and Peace", "Tolstoy, Leo", 1869)
hitchhikersGuide = Book("Hitchhiker's Guide to the Galaxy, The", "Adams, Douglas", 1985)
#Create library
orangeCountyLibrary = Library("Orange County Public Library", [warAndPeace, hitchhikersGuide])
#Print the current owner of Hitchhiker's Guide
print(hitchhikersGuide.owningLibrary())
My question is: How do I enable the contained object (book) to access the attributes/methods of the container object(library). In my example: to return the "name" variable of the owning library
What I've considered trying:
- Inheritance+super() - but books aren't subclasses of libraries, libraries simply contain books
- Maintaining library characteristics on each book object - but this seems clunky and duplicates data across the library and book objects
I'm sure there is something obvious that I'm missing, but everything I've searched for seems to come back with recommendations for inheritance which doesn't seem to make sense to me. Thanks for your help!
Book.SetLibrary(lib)and a__myLibrary__insideBookowningLibrarydoesn't seem like a methodBookshould even have.