实际应用

个人博客

pymysql链接池、事物的使用浅谈

自定义文件操作的类

class myopen:
    def __init__(self,path,mode='r'):
        self.path = path
        self.mode = mode

    def __enter__(self):
        print('start')
        self.f = open(self.path,mode=self.mode)
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()
        print('exit')

with myopen('userinfo','a') as f:
    f.write('hello,world')

实例:pickle的dump与load的类

import pickle


# dump
class MypickleDump:
    def __init__(self,path,mode = 'ab'):
        self.path = path
        self.mode = mode

    def __enter__(self):
        self.f = open(self.path,self.mode)
        return self

    def dump(self,obj):
        pickle.dump(obj,self.f)

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

with MypickleDump('pickle_file') as pickle_obj:
    pickle_obj.dump({1,2,3})

# load
class MypickelLoad:
    def __init__(self,path,mode='rb'):
        self.path = path
        self.mode = mode

    def __enter__(self):
        self.f = open(self.path,self.mode)
        return self

    def loaditer(self):
        while True:
            try:
                # 生成器
                ret = pickle.load(self.f)
                yield ret
            except EOFError:
                break

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.f.close()

with MypickelLoad("pickle_file") as p2:
    content = p2.loaditer()
    for i in content:
        print(i)

在一个函数前后添加功能

import time
class Timer:
    def __enter__(self):
        self.start = time.time()
    def __exit__(self, exc_type, exc_val, exc_tb):
        print(time.time() - self.start)

def func():
    print('wahaha')
    time.sleep(1)
    print('qqxing')


with Timer():
    func()