Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Destructor delayed

Because the object has a reference to itself. (Python uses both reference count and garbage collection.)

class Thing:
    def __init__(self, name):
        self.name = name
        print(f'__init__ {name}')

    def __del__(self):
        print(f'__del__ {self.name}')

def main():
    a = Thing('A')
    b = Thing('B')
    a.partner = a
    print('in main - after')

main()
print('after main')

__init__ A
__init__ B
in main - after
__del__ B
after main
__del__ A