日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 单例模式的实现方法_python中单例模式的四种实现方式

發布時間:2023/12/20 python 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 单例模式的实现方法_python中单例模式的四种实现方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

配置文件settings.py

IP='100.0.0.2'

PORT=3302

方式一:綁定給類的方法

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()

obj = Mysql('1.1.1.0', 3302)

print(obj)

print(obj1)

print(obj2)

print(obj3)

方式二:裝飾器

def singleton(cls):

# 先造好一個空對象

instance = cls(settings.IP, settings.PORT)

def wrapper(*args, **kwargs):

if args or kwargs: # args 和 kwargs 有值時,返回obj

obj = cls(*args, **kwargs)

return obj

return instance

return wrapper

@singleton

class Mysql: # Mysql = singleton(Mysql)

def __init__(self, ip, port):

self.ip = ip

self.port = port

obj1 = Mysql() # wrapper()

obj2 = Mysql()

obj3 = Mysql()

obj4 = Mysql('1.1.1.2', 3303)

print(obj1)

print(obj2)

print(obj3)

print(obj4)

方式三:自定義元類

class Mymeta(type):

def __init__(self, class_name, class_base, class_dic):

# 先造好一個空對象

self.instance = self(settings.IP, settings.PORT)

def __call__(self, *args, **kwargs):

if args or kwargs:

# 拿到一個空對象

obj = self.__new__(self)

# 執行__init__方法為對象初始化屬性

self.__init__(obj, *args, **kwargs)

# 返回一個實例化好的對象

return obj

return self.instance

class Mysql(metaclass=Mymeta):

def __init__(self, ip, port):

self.ip = ip

self.port = port

obj1 = Mysql() # 調用Mysql就是調用__call__方法

obj2 = Mysql()

obj3 = Mysql()

obj4 = Mysql('1.1.1.4', 3301)

print(obj1)

print(obj2)

print(obj3)

print(obj4)

方式四:利用模塊的導入特性

importsettingsclassMysql:def __init__(self, ip, port):

self.ip=ip

self.port=port

instance= Mysql(settings.IP,settings.PORT)

singleton.py

def f1():

from singleton import instance

print(instance)

def f2():

from singleton import instance, Mysql

print(instance)

obj = Mysql('1.1.1.0', 3303)

print(obj)

f1()

f2()

總結

以上是生活随笔為你收集整理的python 单例模式的实现方法_python中单例模式的四种实现方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。