Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

python - What happens if you delete an object that holds another object?

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?

question from:https://stackoverflow.com/questions/65646995/what-happens-if-you-delete-an-object-that-holds-another-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...