【从C#走进python】一、上下文管理器
2021-04-26 16:27
                         标签:--   字典   上下   读取文件   窗体   padding   static   语句   __exit__      我个人对python的学习没有那么系统,一开始想改造引用的类库,发现自己被一些语法问题卡顿,效率就低了。   于是就很想看看C#与python的比较,感觉这样切语言适应起来会舒服些,我就自己写吧。   买了一本书《深入理解Python特性》,嗯我总觉得那些像字典一样的书实在难以提升我的学习兴趣,这本书就很有意思,我就非常喜欢笔者像和你聊天一样介绍“有意思的事情”这样的博客体。 上下文管理器 C# Python using(variable) {..} with variable:     … IDispose   __enter__ __exit__ using语句中使用的类型必须可隐式转换为”System.IDisposable” using括号内应该放一个实现了IDispose接口的变量, 下示一简单例子:   with后接的变量需要实现: __enter__和__exit__ 比起C#用初始化来控制上下文管理器的“开”, 我觉得用单独的enter来控制会合理些。         当using的时候开辟新空间,dispose()用于释放非托管资源; 像是读取文件用完需要close,窗体对象也需要自行销毁,数据库连接断开等; 当然,也可以用try{}catch{}finally{}于finally中释放对象, 但using就是个语法糖嘛。 上例代码主要是一个执行时间的监控, 需要注意的是,exit的入参是规定这样四个参数的,缺一个都不是解释器识别的释放函数。     【从C#走进python】一、上下文管理器 标签:--   字典   上下   读取文件   窗体   padding   static   语句   __exit__    原文地址:https://www.cnblogs.com/carmen-019/p/13252080.html
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
using static System.Console;
    public class testDecorator : IDisposable
    {
        public testDecorator()
        {
            WriteLine("----------start----------");
        }
        public void Dispose()
        {
            WriteLine("---------- end ----------");
        }
    }
using (var td = new testDecorator())
{
    WriteLine($"{DateTime.Now.ToString("yyyyMMddHHmmss")}");
}
 
import time
class manager_exectime():
    def __init__(self):
        self.lst = []
    def __enter__(self):
        self.lst.append(time.time())
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):       
        _ = time.time()
        print(f‘--started at:{str(self.lst[-1])}‘)
        print(f‘--end at:{str(_)}‘)
        print(f‘--used time: {_ - self.lst[-1]}s\n‘)
        self.lst.pop()
try:
    with manager_exectime() as et:
        time.sleep(0.5)
        with et:
            time.sleep(0.5)
except Exception as ex:
    print(str(ex))