0
点赞
收藏
分享

微信扫一扫

with open as f原理解析

infgrad 2022-06-16 阅读 61

1.with语句的原理:

  1.1with是对类进行操作,必须包括以下三个函数

    1.1.1    def __enter__(self):return self     必须返回自己

    1.1.2    def __exit__(self, exc_type, exc_val, exc_tb):关闭类之前做的操作

    1.1.3    具体做事情的函数,名字随便起

2.直接见代码:

with open as f原理解析_函数with open as f原理解析_函数_02

class OPEN():
def __enter__(self):
print("in")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("out")

def do_something(self):
print("做一些事情")
with OPEN() as f:
f.do_something()

View Code

 

  

-----------------------------------------------------------------------------------------------------------------------------------------

举报

相关推荐

0 条评论