[Python] Explaining Python's '__enter__' and '__exit__'

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

    I saw this in someone's code. What does it mean?

    def __enter__(self):
    return self

    def __exit__(self, type, value, tb):
    self.stream.close()


    Here is the complete code.

    from __future__ import with_statement#for python2.5

    class a(object):
    def __enter__(self):
    print 'sss'
    return 'sss111'
    def __exit__(self ,type, value, traceback):
    print 'ok'
    return False

    with a() as s:
    print s


    print s

    Continue reading...

Compartilhe esta Página