一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

腳本之家,腳本語言編程技術及教程分享平臺!
分類導航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服務器之家 - 腳本之家 - Python - Python使用metaclass實現Singleton模式的方法

Python使用metaclass實現Singleton模式的方法

2020-06-22 09:56鴣斑兔 Python

這篇文章主要介紹了Python使用metaclass實現Singleton模式的方法,實例分析了Python基于metaclass實現單例模式的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下

本文實例講述了Python使用metaclass實現Singleton模式的方法。分享給大家供大家參考。具體實現方法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Singleton(type):
  def __call__(cls, *args, **kwargs):
    print "Singleton call"
    if not hasattr(cls, 'instance'):
      cls.instance = super(Singleton, cls).__call__(*args, **kwargs)
    return cls.instance
  def __new__(cls, name, bases, dct):
    print "Singleton new"
    return type.__new__(cls, name, bases, dct)
  def __init__(cls, name, bases, dct):
    print "Singleton init"
    super(Singleton, cls).__init__(name, bases, dct)
class Cache(object):
  __metaclass__ = Singleton
  def __new__(cls, *args, **kwargs):
    print "Cache new"
    return object.__new__(cls, *args, **kwargs)
  def __init__(cls, *args, **kwargs):
    print "Cache init"
  def __call__(cls, *args, **kwargs):
    print "Cache call"
print Cache()
print Cache()

輸出:

?
1
2
3
4
5
6
7
8
Singleton new
Singleton init
Singleton call
Cache new
Cache init
<__main__.Cache object at 0x01CDB130>
Singleton call
<__main__.Cache object at 0x01CDB130>

希望本文所述對大家的Python程序設計有所幫助。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: www.毛片在线观看 | 四虎成人免费 | 九九99亚洲精品久久久久 | 亚洲一欧洲中文字幕在线 | 成年人免费观看的视频 | 色综合合久久天天综合绕视看 | 久久久久久久久a免费 | 国色天香 社区视频 | 亚洲精品福利在线 | 国产成+人+综合+亚洲不卡 | 国产色站 | 99热这里只有精 | 男人的天堂在线观看入口 | 男女做污事 | 石原莉奈adn093店长未婚妻 | 天天久久影视色香综合网 | 舔大逼 | 免费一级片在线观看 | 久久久久久久久a免费 | 99精品热| 国产亚洲成归v人片在线观看 | 亚洲阿v天堂2018在线观看 | 欧美国产视频 | 好大好硬好深好爽gif图 | 果冻传媒和91制片厂网站软件 | 国产精品美女久久久久网站 | 91久久国产成人免费观看资源 | 91免费高清视频 | 亚洲va精品中文字幕 | 亚洲精品久久久久福利网站 | 免费成年人在线视频 | 久久噜国产精品拍拍拍拍 | bdsm中国精品调教 | 国产小青蛙 | 色综合天天综合网站中国 | 国产成人h视频在线播放网站 | 色亚洲色图| 2019中文字幕在线视频 | 免费福利资源站在线视频 | 男人狂擦女人的下面视频 | 调教人妖|