python学习----8.28---单例模式,网络编程

单例模式:多次实例化的结果指向同一个实例

  单例实现方式1

import settings

class MySQL:
    __instance=None
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    @classmethod
    def from_conf(cls):
        if cls.__instance is None:
            cls.__instance=cls(settings.IP, settings.PORT)
        return cls.__instance
obj1=MySQL.from_conf()
obj2=MySQL.from_conf()
obj3=MySQL.from_conf()
# obj4=MySQL('1.1.1.3',3302)
print(obj1)
print(obj2)
print(obj3)
# print(obj4)
View Code

    单例实现方式2(装饰器)

import settings

def singleton(cls):
    _instance=cls(settings.IP,settings.PORT)
    def wrapper(*args,**kwargs):
        if len(args) !=0 or len(kwargs) !=0:
            obj=cls(*args,**kwargs)
            return obj
        return _instance
    return wrapper

@singleton #MySQL=singleton(MySQL) #MySQL=wrapper
class MySQL:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

# obj=MySQL('1.1.1.1',3306) #obj=wrapper('1.1.1.1',3306)
# print(obj.__dict__)

obj1=MySQL() #wrapper()
obj2=MySQL() #wrapper()
obj3=MySQL() #wrapper()
obj4=MySQL('1.1.1.3',3302) #wrapper('1.1.1.3',3302)
print(obj1)
print(obj2)
print(obj3)
print(obj4)
View Code

    单例实现方式3(元类)

import settings

class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        #self=MySQL这个类
        self.__instance=self(settings.IP,settings.PORT)

    def __call__(self, *args, **kwargs):
        # self=MySQL这个类
        if len(args) != 0 or len(kwargs) != 0:
            obj=self.__new__(self)
            self.__init__(obj,*args, **kwargs)
            return obj
        else:
            return self.__instance

class MySQL(metaclass=Mymeta): #MySQL=Mymeta(...)
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port


obj1=MySQL()
obj2=MySQL()
obj3=MySQL()
obj4=MySQL('1.1.1.3',3302)
print(obj1)
print(obj2)
print(obj3)
print(obj4)
View Code

    单例实现方式4(模块导入)

def f1():
    from singleton import instance
    print(instance)

def f2():
    from singleton import instance,My
    SQL
    print(instance)
    obj=MySQL('1.1.1.3',3302)
    print(obj)

f1()
f2()
View Code
import setting

class MySQL:
    print(('run.....'))
    def __init__(self,ip,port):
        self.ip=ip
        self.port=port

instance=MySQL(setting.IP,setting.PORT)
View Code

网络编程

1. 目标:编写一个C/S架构的软件
C/S: Client--------基于网络----------Server
B/S: Browser-------基于网络----------Server

2. 服务端需要遵循的原则:
1. 服务端与客户端都需要有唯一的地址,但是服务端的地址必须固定/绑定
2. 对外一直提供服务,稳定运行
3. 服务端应该支持并发

3. 网路
网络建立的目的是为数据交互(通信)
如何实现通信:
1. 建立好底层的物理连接介质
2. 有一套统一的通信标准,称之为互联网协议

4. 互联网协议:就是计算机界的英语
OSI七层协议
      应用层
      表示层
      会话层
      传输层
      网络层
      数据链路层
      物理层


ip+mac可以标识全世界范围内独一无二的一台计算机的位置
port可以标识一台计算机之上唯一的一个基于网络通信的应用软件

ip+mac+port:可以标识全世界范围内独一无二的一个应用软件(基于网络通信)
原文地址:https://www.cnblogs.com/Liu-guang-hui/p/9550128.html