Python單例模式

1.單例模式要點

  • 某個類只有一個實例;
  • 類必須自行創建實例
  • 必須自行向系統提供這個實例

2.實現單例模式方法

  • 使用模塊
  • 使用__new__
  • 使用裝飾器(decorator)
  • 使用元類(metaclass)

3.模塊

一:將類保存到test1.py文件中

#test1.py

class Opt(object):

    def foo(self):

        print("hello")

my_opt = Opt()

二:獲取一個單例對象

from .test1 import my_opt

my_opt.foo()


4.使用__new__

說明:__init__和__new__的區別,__init__是類實例初始化的時候調用的,__new__是類創建實例的時候調用的,故而可以使用__new__來創建單例模式。

class Singleton(object):

    def __new__(cls,*args,**kwargs):

        if not hasattr(cls, '_instance'):

            cls._instance = Super(Singleton,cls).__new__(cls,*args,**kwargs)

        return cls._instance

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章