# -*- coding: UTF-8 -*- # 单例模型 # 重写new方法 class Mysingleton(object): __obj = None __init_flag = True def __new__(cls, *args, **kwargs): if cls.__obj == None: cls.__obj = super(Mysingleton, cls).__new__(cls, *args, **kwargs) # cls.__obj = object.__new__(cls) return cls.__obj def __init__(self, name): if Mysingleton.__init_flag: print '666666' self.name = name Mysingleton.__init_flag = False a = Mysingleton('aa') b = Mysingleton('bb') print a print b # 用装饰器实现 from functools import wraps def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): '''decorator''' print('Decorated function...') return func(*args, **kwargs) return wrapper @my_decorator def test(): '''Testword''' print('Test function') print(test.__name__, test.__doc__) # 工厂模式 class Factory(object): def create_car(self, brand, *args, **kwargs): if brand == '奔驰': return Benz(*args, **kwargs) elif brand == '宝马': return BMW(*args, **kwargs) elif brand == '比亚迪': return BYD(*args, **kwargs) else: return '未知品牌,无法创建' class Benz(object): def __init__(self, clour): self.clour = clour def car(self): print '这辆奔驰是{}颜色的'.format(self.clour) pass class BMW(object): def __init__(self, clour): self.clour = clour def car(self): print '这辆宝马是{}颜色的'.format(self.clour) class BYD(object): def __init__(self, clour): self.clour = clour def car(self): print '这辆比亚迪是{}的'.format(self.clour) factory = Factory() car1 = factory.create_car('宝马', '红色') car1.car()
# 写一个装饰器,用于打印函数执行时长及执行次数 import time def decorator(func): count = 0 def deco(*args, **kwargs): # nonlocal count start_time = time.time() data = func(*args, **kwargs) end_time = time.time() dt = end_time - start_time print '本次调用花费时间{}秒,本次调用为第{}次。'.format(dt, count) count += 1 return data return deco @decorator def func(n): print 'hello world', n time.sleep(1) if __name__ == '__main__': for i in range(3): func(i)