with statement work on class

后端 未结 2 631
抹茶落季
抹茶落季 2021-01-13 17:11
{class foo(object):
    def __enter__ (self):
        print(\"Enter\")
    def __exit__(self,type,value,traceback):
        print(\"Exit\")
    def method(self):
            


        
相关标签:
2条回答
  • 2021-01-13 17:56

    The problem is that your __enter__ method does not return self.

    0 讨论(0)
  • 2021-01-13 17:58

    __enter__ should return self:

    class foo(object):
        def __enter__ (self):
            print("Enter")
            return self
        def __exit__(self,type,value,traceback):
            print("Exit")
        def method(self):
            print("Method")
    with foo() as instant:
        instant.method()
    

    yields

    Enter
    Method
    Exit
    

    If __enter__ does not return self, then it returns None by default. Thus, instant is assigned the value None. This is why you get the error message

    'NoneType' object has no attribute 'method'

    (my emphasis)

    0 讨论(0)
提交回复
热议问题