0

Let's say I have two classes:

import matplotlib.pyplot as plt

class AClass:
    def __init__(self):
        self.A = SomeStuff()
        self.B = plt.figure(1)
    def SomeOtherThings(self):
        MaybeIPlotSomeThingsToThatPlotEtc
        ....

class AnotherClass:
    def __init__(self):
        self.AClassWithinAClass = AClass()
        self.B = plt.figure(2)
    def SomeOtherThings(self):
        MaybeIPlotSomeThingsToThatPlotEtc
        ....

In C++, when I put an object into another object as a POINTER to that object, I have to, HAVE to delete it in a destructor or it is a memory leak.

Question 1: In the above pseudocode, is self.B the kind of pointer that I need to delete in a destructor?

Question 2: What about the variable AClassWithinAClass? Is that a pointer that I need to delete in a destructor, or does python know to get rid of it when the AnotherClass gets deleted?

I've tried googling about pointers and stuff (Pointers in Python?) but I guess I'm nervous because python is such an implicit language.

1 Answers1

0

In both of these cases you do not need to explicitly call a destructor method. Python uses garbage collection to manage memory. To maintain this it uses reference counting. Python will keep a count of how many variables reference a particular object. However, if Python has a variable that is not referenced by anything it will free the memory. I'm certainly not an expert on the internal memory management of Python but that's my understanding.

Previous StackOverflow Post

Kyle
  • 1,056
  • 5
  • 15