单例模式和装饰器

  1. new方法实现单例模式
class Singleton(object):
    def __new__(cls,*args,**kwargs):
        if not hasattr(cls,'_instance'):
            cls._instance = super(Singleton,cls).__new__(cls,*args,**kwargs)
        return cls._instance
  1. 装饰器
from time import time
import datetime
def wrap(func):
    def timer(*args,**kwargs):
        t1 = time()
        temp_time = datetime.datetime.now()
        func()
        t2 = time()
        result = t2-t1
        start_time = temp_time.strftime('%c')
        print('the start time is %s' % start_time)
        print("the running time is %f seconds" % result)
    return timer

@wrap
def functions():
    for i in range(1000):
        print (i)

functions()

你可能感兴趣的:(单例模式和装饰器)