杰瑞科技汇

Python对象删除后,内存如何回收?

Of course! In Python, deleting an object is a fundamental concept tied to memory management. Let's break it down into three main levels:

  1. Deleting a Variable Reference (The most common use case)
  2. Deleting an Object's Attributes
  3. Explicitly Deleting an Object (Less common and often unnecessary)

Deleting a Variable Reference (Using del)

When you create a variable in Python, you are creating a reference to an object in memory. The del statement doesn't delete the object itself; it deletes the variable name (the reference). If no other references to the object exist, the object becomes "unreachable," and Python's garbage collector will automatically reclaim the memory it occupies.

How it Works:

# 1. Create a list object and assign it to the variable 'my_list'
my_list = [1, 2, 3, 4]
print(f"my_list exists: {my_list}")  # Output: my_list exists: [1, 2, 3, 4]
# 2. Create another reference to the SAME list object
another_reference = my_list
print(f"another_reference points to: {another_reference}") # Output: [1, 2, 3, 4]
# 3. Delete the 'my_list' reference
del my_list
# 4. Try to use 'my_list' now. This will raise a NameError.
try:
    print(my_list)
except NameError as e:
    print(f"Error: {e}") # Output: Error: name 'my_list' is not defined
# 5. Check 'another_reference'. The object still exists because another reference points to it.
print(f"another_reference still points to: {another_reference}") # Output: [1, 2, 3, 4]
# 6. Now, delete the last reference to the object
del another_reference
# After this, the list object [1, 2, 3, 4] is now unreachable.
# The garbage collector will free the memory it was using.
# You can't prove it's gone, but you know it will be collected.

Key Takeaway:

del my_variable removes the name my_variable from the current namespace. If that was the last name pointing to the object, the object is scheduled for deletion by the garbage collector.


Deleting an Object's Attributes

You can also use del to remove an attribute from an object.

How it Works:

class Car:
    def __init__(self, make, model):
        self.make = make
        self.model = model
        self.year = 2025  # An attribute we might want to delete later
my_car = Car("Toyota", "Corolla")
# Print attributes before deletion
print(f"Car attributes: {my_car.__dict__}")
# Output: Car attributes: {'make': 'Toyota', 'model': 'Corolla', 'year': 2025}
# Delete the 'year' attribute from the my_car object
del my_car.year
# Print attributes after deletion
print(f"Car attributes after deletion: {my_car.__dict__}")
# Output: Car attributes after deletion: {'make': 'Toyota', 'model': 'Corolla'}
# Trying to access the deleted attribute will raise an AttributeError
try:
    print(my_car.year)
except AttributeError as e:
    print(f"Error: {e}")
# Output: Error: 'Car' object has no attribute 'year'

Explicitly Deleting an Object (When and Why You Shouldn't)

You might see code that tries to delete an object directly using del obj. While this works, it's often considered bad practice in Python.

# Create a large object
import sys
data = ["a"] * 10_000_000  # A list with 10 million items
# Get its memory size (approximate)
print(f"Size of data: {sys.getsizeof(data) / (1024 * 1024):.2f} MB") # Output: Size of data: 76.29 MB
# Delete the reference
del data
# Manually trigger the garbage collector (usually not needed)
import gc
gc.collect()
# Now, the memory should be freed.
# If you try to create another large object, you'll see the memory usage drop.

Why is this often bad practice?

  1. Garbage Collection is Automatic: Python has a sophisticated and automatic garbage collector. It's designed to handle object cleanup efficiently. You almost never need to manually intervene.
  2. Readability and Intent: Using del on a variable reference clearly communicates that you are done with that name. Using del obj can be confusing. It implies you are managing memory manually, which is not the Pythonic way.
  3. Cyclic References: The main reason for a manual gc.collect() is to handle cyclic references (objects that refer to each other in a loop, preventing the standard garbage collector from deleting them). However, even in these cases, it's better to fix the design that creates the cycle than to manually collect garbage.

The Pythonic Way: Instead of deleting objects, you should focus on removing references. When a function ends, its local variables are automatically dereferenced. When you reassign a variable, the old object it pointed to may become unreachable.

Summary

Action Command What it Does When to Use
Delete a Variable Reference del my_variable Removes the name my_variable from the current scope. The object may be deleted by the GC if no other references exist. Very common. Use when you want to remove a name from a namespace or ensure an object can be garbage collected.
Delete an Object Attribute del my_object.attribute Removes the named attribute from the object instance. Common. Use when you want to remove a property from an object, effectively "unsetting" it.
Force Garbage Collection import gc; gc.collect() Forces the garbage collector to run immediately and destroy all unreachable objects. Rare. Only use for debugging memory leaks or in very specific, advanced scenarios involving cyclic references.

Python对象删除后,内存如何回收?-图1

Python对象删除后,内存如何回收?-图2

Python对象删除后,内存如何回收?-图3

分享:
扫描分享到社交APP
上一篇
下一篇