Deleting class B when calling __del__ of class A

If you want to be 100% certain the books go out of scope at the same time as the shelves (and the shelves at the same time as the library), then I am not aware of an easier way to do it.

But I would really encourage you to not worry about this and let the garbage collector handle it. That is literally what it’s for. Unless you are dealing with very memory intensive objects, this sort of optimization is more trouble than it’s worth.