python 杂记

一、不知道取啥名

1、with

它是一种上下文管理协议,目的在于从流程图中把 try,except 和finally 关键字和
资源分配释放相关代码统统去掉,简化try….except….finlally的处理流程
with通过__enter__方法初始化,然后在__exit__中做善后以及处理异常。

所以使用with处理的对象必须有__enter__()和__exit__()这两个方法。

class mytest():
    def __init__(self,n,a,w):
        self.name = n
        self.age = a
        self.weight = w

    def __enter__(self):
        print("enter 方法被执行了")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
         print("exit 方法被执行了")

    def show(self):
        print("this is show 方法,输出了:"+self.name)
# test = 

with mytest("hzx","20","140") as file:
    file.show()

输出为

enter 方法被执行了
this is show 方法,输出了:hzx
exit 方法被执行了

os模块

https://blog.csdn.net/weixin_38507813/article/details/87797839

posted @ 2021-01-03 23:44  vstar_o  阅读(62)  评论(0)    收藏  举报