python ref counting based garbage collection

Wenyang發表於2019-06-20

不用中文都不讓釋出

class Foo:
def __init__(self):
    self.other = None
def ref(self, other):
    self.other = other
def __del__(self):
    print('Foo instance deletion')

# case 1
f = Foo()
del f   # you should see deletion msg here

# case 2
f = Foo()
g = Foo()
f.ref(g)
del g
del f   # you should see two deletion msgs here

# case 3
f = Foo()
g = Foo()
f.ref(g)
g.ref(f)    # create circle refs   
del f
del g
# you wont see any deletion msg above
import gc
gc.collect()
# now you will see it

def foo():
try:
    print('in')
    yield
finally:
    print('out')
# case 1
f = foo()
del f
# case 2
f = foo()
next(f)
del f

相關文章