Reference Counting and Object Lifetimes
Pyyhkäise näyttääksesi valikon
Every object in Python has a reference count – a number tracking how many variables, containers, or other objects point to it. When that count reaches zero, Python deallocates the object immediately. This is the primary memory management mechanism in CPython.
How Reference Counting Works
Each time you assign an object to a variable, pass it to a function, or store it in a list, the reference count increases. Each time a variable goes out of scope, a list is cleared, or a variable is reassigned, the count decreases.
1234567891011import sys # Creating an object and observing its reference count employee_name = "Alice" print(sys.getrefcount(employee_name)) # At least 2 – one for the variable, one for getrefcount() second_reference = employee_name print(sys.getrefcount(employee_name)) # One more than before del second_reference print(sys.getrefcount(employee_name)) # One less than before
sys.getrefcount() always adds 1 to the count – the function argument itself is a temporary reference. Keep that in mind when reading the output.
Object Lifetime
An object lives as long as at least one reference to it exists. The moment the last reference is removed, CPython deallocates the object and reclaims its memory.
1234567891011121314151617import sys # Tracking object creation and deletion class DataRecord: def __init__(self, record_id): self.record_id = record_id print(f"Record {record_id} created") def __del__(self): print(f"Record {self.record_id} deleted") record = DataRecord(1) # Created second_ref = record # Reference count: 2 del record # Reference count: 1 – not deleted yet print("Before del second_ref") del second_ref # Reference count: 0 – deleted now print("After del second_ref")
For objects not involved in reference cycles, deletion happens exactly when the last reference is removed – not at the end of the program or at some unpredictable time.
What Increases the Reference Count
The reference count increases when:
- A variable is assigned an object (
name = obj); - An object is added to a container (
my_list.append(obj)); - An object is passed as a function argument;
- An object is returned from a function.
What Decreases the Reference Count
The reference count decreases when:
- A variable is deleted (
del name); - A variable is reassigned (
name = other_obj); - A variable goes out of scope (function returns);
- An object is removed from a container (
my_list.remove(obj)).
Checking Reference Counts in Practice
1234567891011121314import sys # Observing reference count changes in a list class BudgetItem: def __init__(self, label): self.label = label budget_items = [BudgetItem("rent"), BudgetItem("salaries"), BudgetItem("equipment")] item = budget_items[0] print(sys.getrefcount(budget_items[0])) # 3 – list slot + item variable + getrefcount arg budget_items.clear() print(sys.getrefcount(item)) # 2 – only item variable + getrefcount arg remains
Kiitos palautteestasi!
Kysy tekoälyä
Kysy tekoälyä
Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme