For some reason, I need to be able to delete all the children (in some sense) that were originated by some method of the class. Here is an example:
class A():
def __init__(self):
self.a_val = 56
self.children = list()
def __del__(self):
del self.children
def gen_b(self):
return B(self.a_val)
class B():
def __init__(self, val):
self.a_val = val
self.b_val = 87
What I want is somehow to append generated class B from gen_b
to A().children
so that:
a_class = A()
b_generated = a_class.gen_b()
del a_class
# b_generated is also deleted
Additionally, I need this for cython (I use cdef classes), so maybe there are some solutions with __dealloc__
or other Cython specific notations. All the solutions will be appreciated.
What I want is somehow to append generated class B from gen_b to A().children
Just store the new element before returning it and you can do whatever you want with it - including adding to children
def gen_b(self):
b = B(self.a_val)
self.children.append(b)
return b
As for del
... Please read what del actually does. The most important part is:
Deletion of a name removes the binding of that name
So if you do e.g.
>>> a_class = A()
>>> a2 = a_class
>>> del a_class
a2 still will work and target the same element (because it holds the same reference that a_class
did). del
just deletes the name, not the object itself.
You would need a different approach to delete those elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With