If I create an instance of a class without assigning it to a variable will it occupy memory every time I run the code? Or does the memory free up after the line of code containing the instance is executed?
For example:
class TestClass():
def __init__(self):
self.Moto = "Moto"
def printIt(self):
print self.Moto
So if I use it like this:
TestClass().printIt()
Does it occupy more and more memory every time the line is executed?
No, the instance will be automatically garbage collected. The exact mechanism depends on the Python implementation. CPython uses reference counting and will free the instance at the end of
TestClass().printIt().If, however, you were to retain one or more references to the newly constructed object, the object would be kept alive for as long as it’s being referenced.