with statement work on class

假装没事ソ 提交于 2019-12-01 05:52:10

问题


{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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/16533794/with-statement-work-on-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!