Last active
January 10, 2022 00:24
-
-
Save mengzhuo/9809429 to your computer and use it in GitHub Desktop.
weakref demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import weakref | |
class ExpensiveObject(object): | |
def __init__(self, name): | |
self.name = name | |
def __del__(self): | |
print '(Deleting %s)' % self | |
obj = ExpensiveObject('Cake') | |
r = weakref.ref(obj) | |
p = weakref.proxy(obj) | |
print 'via obj', obj.name # Cake | |
print 'via ref', r().name # Cake | |
print 'via proxy', p.name # Cake | |
del obj | |
print 'ref', r() # None | |
print 'proxy:', p.name # raised |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment