class Con:
def __enter__(self):
print('__enter__方法被调用执行了')
def __exit__(self, exc_type, exc_val, exc_tb):
print('__exit__方法被调用执行了')
def help(self):
print('123123123')
with Con() as file: #相当于file=Contentmanager()
file.help()
file.help()这一句会报错,AttributeError: 'NoneType' object has no attribute 'help'
求解答,为什么我的with语句无法调用自定义的类方法?
with语句在求出这个上下文管理器对象之后,自动执行进入方法,并将这个对象的返回值赋值于 as 之后的变量,然后执行语句块。由于进入语句块没有返回值,在相继执行完前面两个方法后,再执行help方法时,此时self为None,无help方法。如果要调用执行help方法,可以在__enter__中加上return self。
class Con:
def __enter__(self):
print('__enter__方法被调用执行了')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('__exit__方法被调用执行了')
def help(self):
print('123123123')
with Con() as f: # 相当于file=Contentmanager()
f.help()