一、知识点拾遗
1、多继承的易错点
二、设计模式
1、设计模式介绍
Gof设计模式
大话设计模式
2、单例模式
- 当所有实例中封装的数据相同时,使用单例模式
- 静态方法+静态字段
- 单例就是只有一个实例
a。创建单例模式应用场景和实例
①创建一个数据库连接池
1 class ConnectionPool 2 3 __instance=None 4 5 def__init__(self): 6 self.ip="1.1.1.1" 7 self.port=3307 8 self.pwd="567678" 9 self.username="minmin"10 self.conn_list=[1,2,3,4,5,6,7,8,9,10]11 12 13 @staticmethond14 def get_instance():15 if ConnectionPool.__instance:16 return ConnectionPool.__instance17 else:18 #/创建一个对象,并将对象赋值给静态字段__instance19 ConnectionPool.__instance=ConnectionPool()20 return ConnectionPool.__instance21 22 def get_coonection(self):23 #获取连接24 import random25 r = random.randrange(1,11)26 return r27 28 29 obj1=ConnectPool.get_instance()30 print(obj1)31 obj2=ConnectPool.get_instance()32 print(obj2)33 obj3=ConnectPool.get_instance()34 print(obj3)
②创建web站点并应用单例模式
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 5 form wsgiref.simple_server import make_server 6 import random 7 class ConnectionPool: 8 9 10 __instance = None11 12 def __init__(self):13 self.ip = "1.1.1.1"14 self.port=330715 self.pwd="567678"16 self.username="124"17 self.conn_list = [1, 2, 3, 4, 5, 6, 7, 8, 9,10]18 19 20 @staticmethod21 def get_instance():22 if ConnectionPool.__instance:23 return ConnectionPool.__instance24 else:25 26 # 创建一个对象,并将对象赋值给静态字段__instance27 ConnectionPool.__instance = ConnectionPool()28 return ConnectionPool.__instance29 30 def get_connection(self):31 #获取连接32 r = random.randrange(1,11)33 return r34 35 def index():36 p = ConnectionPool.get_instance()37 print(p)38 conn = ConnectionPool.get_connection()39 return "11111111111"+str(conn)40 41 def news():42 return "123124"43 def RunServer(environ,start_response):44 start_response(status='200 OK',headers=[('Content-Type','text/html')])45 url=environ['PATH_INFO']46 if url.endswith('index'):47 ret = index()48 return ret49 elif url.endswith('news'):50 ret = news()51 return ret52 else:53 return '404'54 55 if __name__=='__main__':56 httpd=make_server('', 8000, RunServer)57 print("Serving HTTP on port 8000.....")58 httpd.serve_forever()单例单例