Object References in Practice
Real-World Reference Scenarios
Function Parameter Passing
In Python, objects are passed by reference, which can lead to unexpected behaviors:
def modify_list(lst):
lst.append(4) ## Modifies the original list
lst = [5, 6, 7] ## Creates a new local reference
original = [1, 2, 3]
modify_list(original)
print(original) ## [1, 2, 3, 4]
graph TD
A[Original List] -->|Reference Passed| B[Function Parameter]
B -->|Modification| A
Reference Patterns in Classes
class DataProcessor:
def __init__(self, data):
self.data = data ## Reference to input data
def process(self):
## Modifies the original reference
self.data = [x * 2 for x in self.data]
## Usage example
original_data = [1, 2, 3]
processor = DataProcessor(original_data)
processor.process()
print(original_data) ## [2, 4, 6]
Reference Copying Techniques
Copying Method |
Description |
Use Case |
Shallow Copy |
list.copy() |
Copies top-level structure |
Deep Copy |
copy.deepcopy() |
Copies nested structures |
Slice Copy |
list[:] |
Creates a new list instance |
Demonstration of Copying
import copy
## Shallow copy
original = [1, [2, 3], 4]
shallow_copy = original.copy()
shallow_copy[1][0] = 'X'
print(original) ## [1, ['X', 3], 4]
## Deep copy
deep_copy = copy.deepcopy(original)
deep_copy[1][0] = 'Y'
print(original) ## [1, ['X', 3], 4]
Advanced Reference Manipulation
Reference Counting
import sys
x = [1, 2, 3]
y = x
## Check reference count
print(sys.getrefcount(x)) ## Typically 3 (x, y, and function argument)
Weak References
import weakref
class ExpensiveObject:
def __init__(self, value):
self.value = value
## Create a weak reference
obj = ExpensiveObject(42)
weak_ref = weakref.ref(obj)
## Accessing the object
print(weak_ref().value) ## 42
- Minimize unnecessary object creation
- Use reference-efficient data structures
- Be mindful of memory usage
At LabEx, we emphasize understanding these reference mechanisms to write more efficient Python code.