with statement work on class

2020-03-24 05:19发布

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

Execute this py file and console shows these message:

Enter
Exit

instant.method()
AttributeError: 'NoneType' object has no attribute 'method'

unable to find methods?

2条回答
forever°为你锁心
2楼-- · 2020-03-24 05:56

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

查看更多
神经病院院长
3楼-- · 2020-03-24 06:11

__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)

查看更多
登录 后发表回答