Hello everybody,
I am a newcomer in OOP and I am trying to code my own __del__ method.
I would need some advice to organize my code.
As an exercise, I would like to create a virtual storage furniture.
In this storage furnitures, there are several shelves.
On each shelf, there a k places for CD, DVD or books.
I have organized my code as follow :
- The storage furniture is
class Libraryinitialized by__init__(self, nb_of_shelves=0)(number of shelves as possible arg).
One of its attribute isself.shelves = [Shelf() for i in range(nb_of_shelves)]with Shelf the class designing one of the library shelves. -
class Shelfis initialized using__init__(self, nb_of_products=0)and with an attributeself.products = [None for i in range(nb_of_products)] - Shelf has methods to add Book, CD or DVD at location k
- Book, CD and DVD are classes with attributes such as name, date, authors …
My willing is to be able to create a library empty or not, with x number of shelves, each shelf having its own product storage capacity and being able to store anything at any location.
I am trying to create custom del methods, to delete every instances if I delete the library or one shelf.
I did like below in the class Library:
(sorry for the unindentation I don’t know how to add it)
def __del__(self):
for each shelf in self.shelves:(I have defined iterator in the class)
print(f"Deleting shelf {shelf.name}")
del shelf
However, when using del lib (with lib an instance of Library) it doesn’t delete sub-instances. But when I re-instanciate lib = Library I can see entering the for loop and deleting all “sub-instances”.
I have two questions:
- Do I am doing well ?
- How can I process to delete my sub-instances ?
Thank you for help,
Loupdmer