Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

with statement work on class

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

like image 977
Zetor Avatar asked Dec 06 '22 07:12

Zetor


2 Answers

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

like image 90
unutbu Avatar answered Dec 25 '22 15:12

unutbu


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

like image 30
isaach1000 Avatar answered Dec 25 '22 13:12

isaach1000