Python入门学习-DAY30-单例模式与网络编程入门

单例

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

单例模式实现方式一:

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)        

 单例模式实现方式二:装饰器

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

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)   

单例模式实现方式三:

import settings

class Mymeta(type):
    def __init__(self,class_name,class_bases,class_dic):
        self.__instance=self(settings.IP,settings.PORT)

    def __call__(self, *args, **kwargs):
        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)

'''
# 单例模式实现方式四:

singleton.py

import settings
class Mysql():
    def __init__(self,host,port):
        self.host=host
        self.port=port


instance=Mysql(settings.IP,settings.PORT)
def f1():
    from singleton import instance
    print(instance)

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

f1()
f2()

 网络编程介绍

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/xvchengqi/p/9549713.html