文件读写

  • 一般文件读写可以这样写,但是需要我们手动关闭文件,如果忘记关闭文件,可能导致文件没有写入。

    1. f = open(""filename.txt", "w")
    2. f.write("")
    3. f.close()
  • 如果使用with语句,可以帮助我们读取或者写入文件之后自动关闭文件,不仅增加文件的可读性,还避免了出错。

    1. with open("filename.txt", "w") as f:
    2. f.write("hallo")

类上下文管理器

  • 如果想要在类中使用上下文管理器,就需要两个魔法方法

    • enter(self)
      • 在进行实例化时自动调用,返回一个可调用对象给as后面的对象接收。
    • exit(self, except_type, except_value, except_traceback)
      • 程序运行结束之前自动调用
      • except_type, except_value, except_traceback为异常类型、异常值、异常回溯,如果程序运行正确,这三个值为None
  • 以下程序模拟空调运行,再空调运行一段时间之后自动停止运行,避免了过度使用,造成疲劳 ```python class Machine(object): def enter(self):

    1. print("开启空调 !")
    2. return self

    def run_time(self, t):

    1. print("空调运行中...")
    2. print(f"空调已运行{t}s")

    def decrease_temp(self, num):

    1. print(f"空调已降低{num}度")

    def exit(self, exc_ty, exc_val, exc_trac):

    1. print("关闭空调!")

with Machine() as m: m.run_time(100) m.decrease_temp(100)

  1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/1325594/1594572846667-2f213402-ff8e-4a61-b9a3-441bfc8f26f6.png#align=left&display=inline&height=77&margin=%5Bobject%20Object%5D&name=image.png&originHeight=130&originWidth=1261&size=31370&status=done&style=none&width=746)
  2. <a name="YOxUJ"></a>
  3. #### 函数上下文管理器
  4. - 可以使用@contextlib.contextmanager ,如下,run_sometihng函数将yeild返回的 a 赋值给 r,同时继续向下执行。
  5. ```python
  6. @contextmanager
  7. def run_something():
  8. a = "我说yo你说no"
  9. yield a
  10. print("我还有话说。。。")
  11. with run_something() as r:
  12. print(r)

image.png