国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python單例模式實例解析

2020-01-04 14:37:47
字體:
來源:轉載
供稿:網友

本文實例為大家分享了python單例模式的具體代碼,供大家參考,具體內容如下

多次實例化的結果指向同一個實例

單例模式實現方式

方式一:

import settingsclass 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.__instanceobj1 = MySQL.from_conf()obj2 = MySQL.from_conf()obj3 = MySQL.from_conf()print(obj1)print(obj2)print(obj3)

方式二:

import settingsdef singleton(cls):  _instance = cls(settings.IP, settings.PORT)  def wrapper(*args, **kwargs):    if args or kwargs:      obj = cls(*args, **kwargs)      return obj    return _instance  return wrapper@singletonclass MySQL:  def __init__(self, ip, port):    self.ip = ip    self.port = portobj1 = MySQL()obj2 = MySQL()obj3 = MySQL()print(obj1)print(obj2)print(obj3)

方式三:

import settingsclass Mymeta(type):  def __init__(self, class_name, class_bases, class_dic):    self.__instance = self(settings.IP, settings.PORT)  def __call__(self, *args, **kwargs):    if args or kwargs:      obj = self.__new__(self)      self.__init__(obj, *args, **kwargs)      return obj    else:      return self.__instanceclass MySQL(metaclass=Mymeta):  def __init__(self, ip, port):    self.ip = ip    self.port = portobj1 = MySQL()obj2 = MySQL()obj3 = MySQL()print(obj1)print(obj2)print(obj3)

方式四:

def f1():  from singleton import instance  print(instance)def f2():  from singleton import instance,MySQL  print(instance)  obj = MySQL('1.1.1.1', '3389')  print(obj)f1()f2()singleton.py文件里內容:import settingsclass MySQL:  print('run...')  def __init__(self, ip, port):    self.ip = ip    self.port = portinstance = MySQL(settings.IP, settings.PORT)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 普洱| 沽源县| 团风县| 威远县| 汶川县| 昌乐县| 荥经县| 永康市| 西乌珠穆沁旗| 福清市| 连南| 怀安县| 区。| 双流县| 紫金县| 灌阳县| 新兴县| 昌宁县| 永修县| 广宗县| 贵定县| 新田县| 乌恰县| 宁化县| 山丹县| 海城市| 洪湖市| 新邵县| 中宁县| 同心县| 兴文县| 万州区| 井研县| 海安县| 康保县| 吉安县| 邓州市| 延川县| 延川县| 福泉市| 平邑县|