Object becomes None when using a context manager

后端 未结 3 711
野性不改
野性不改 2020-12-06 16:39

Why doesn`t this work:

class X:
    var1 = 1
    def __enter__(self): pass
    def __exit__(self, type, value, traceback): pass

with X() as z:
    print z.v         


        
3条回答
  •  失恋的感觉
    2020-12-06 17:14

    Change the definition of X to

    class X(object):
        var1 = 1
        def __enter__(self):
            return self
        def __exit__(self, type, value, traceback):
            pass
    

    with assigns the return value of the __enter__() method to the name after as. Your __enter__() returned None, which was assigned to z.

    I also changed the class to a new-style class (which is not critical to make it work).

提交回复
热议问题