2
Hello, I am studying a little more about the best practices of using Python and I came across a command that I do not know very well, the with
, so I decided to study a little bit better about how it works, and I’m trying to take a test, the program I wrote is the following:
class Teste(object):
def __init__(self, var1):
self.var1 = var1
def __enter__(self):
print('Entrou!!')
def __exit__ (self, exception, value, traceback):
print('Saiu!!')
def mostrar_var(self):
print('A variavel é: {}'.format(self.var1))
if __name__ == '__main__':
with Teste('Olá') as objeto_teste:
objeto_teste.mostrar_var()
My intention in this test is to start the Test object, run the "mostrar_var" method and close the object, but I am not able to execute the "mostrar_var" method, just start and end the object. I would like a help to better understand what I am doing wrong and how these methods can be accessed using the with
. The Exception I get running this code is as follows:
Entrou!! Saiu!! Traceback (most recent call last): File "C:\Users\ZanattaJ\Desktop\teste.py", line 14, in <module>
objeto_teste.mostrar_var() AttributeError: 'NoneType' object has no attribute 'mostrar_var'
Related or duplicate: https://answall.com/q/49238/101
– Maniero