2

I'm sorry if the topic in wrong section

I'm curious about Python classes __del__ method:

Example:

class A():
    [...]

class B():
    __init__:
        self.a = A()
    __del__:
        del self.a

b = B()
del b

Do I have to write __del__ method on class B? Is A class instance in B class remove from memory when remove B instance or we must use __del__ method like mine?

ngShravil.py
  • 4,742
  • 3
  • 18
  • 30
AkrepAdam
  • 21
  • 2
  • https://stackoverflow.com/questions/1481488/what-is-the-del-method-how-to-call-it This may help. `Since you have no guarantee it's executed, one should never put the code that you need to be run into __del__()` – clubby789 Oct 11 '19 at 21:17
  • 1
    You never normally need a del method. The usage as shown should not need it. btw methods need brackets: def x(self): – quamrana Oct 11 '19 at 21:22
  • `del b` should suffice. – pylang Oct 11 '19 at 21:42

1 Answers1

2

When the B object is destroyed (after it is “finalized”), its reference a evaporates, so the del a at most adjusts the timing of the destruction of the A object (in a way that is unobservable with the code shown here). “At most” because the timing (or even occurrence) of object finalization/destruction is completely unspecified except that finalization precedes destruction and neither happens while the object is referenced.

Davis Herring
  • 36,443
  • 4
  • 48
  • 76