If I have
class MyClass:
def __init__(self, object):
self.object = object
some_other_object = SomeOtherObject()
myclass = MyClass(some_other_object)
del myclass
what happens to the some_other_object
? Does it get deleted too?
If I have
class MyClass:
def __init__(self, object):
self.object = object
some_other_object = SomeOtherObject()
myclass = MyClass(some_other_object)
del myclass
what happens to the some_other_object
? Does it get deleted too?
If there are no other references to some_other_object
throughout the program, then yes, it too will get deleted.
In your case, there are two references: 1) some_other_object
, and 2) myclass.object
.
Deleting myclass
just deletes the second reference. But the first remains.
Python uses a method of garbage collection called 'reference counting'. To summarise it very concisely, Python keeps track of the number of 'references' to each object in memory. If you run del x
, you're decrementing the number of references to the object that x
referred to by 1 (and the name x
no longer refers to that object, of course). Once the number of references to an object reaches 0, it can be garbage collected (i.e. the memory it occupies can be freed).
There is an assumption in the title "What happens if you delete an object that holds another object?"
You don't actually delete objects with del
, you delete references to objects. When there are no more references to an object, it is garbage-collected and only then does it (and any references inside it) get deleted.
So, in your code:
class MyClass:
def __init__(self, object):
self.object = object
# A new object is created by SomeOtherClass() and assigned to some_other_object
some_other_object = SomeOtherClass()
# A new object is created by MyClass() and the my_object reference is created.
# Inside the new MyClass object my_object, a reference to some_other_object is saved.
my_object = MyClass(some_other_object)
# Here, the reference my_object is deleted, and thus the whole MyClass object is deleted.
# That includes the MyClass.object reference, but there's still the some_other_object reference.
del my_object
# Only now would that object be deleted, as the last reference is deleted.
del some_other_object
I've renamed some of your variables and classes, as you were mixing them - there's of course an important difference between a class and and object and you should pick your object references and class names accordingly (although typically, the word 'object' or 'Class' is omitted).