Python裝飾器實現單例模式

2021-09-02 02:43:08 字數 940 閱讀 4594

# -*- coding: utf-8 -*-

# 使用裝飾器(decorator),

# 這是一種更pythonic,更elegant的方法,

# 單例類本身根本不知道自己是單例的,因為他本身(自己的**)並不是單例的

def singleton(cls, *args, **kw):

instances = {}

def _singleton():

if cls not in instances:

instances[cls] = cls(*args, **kw)

return instances[cls]

return _singleton

@singleton

class myclass4(object):

a = 1

def __init__(self, x=0):

self.x = x

if __name__ == '__main__':

one = myclass4()

two = myclass4()

two.a = 3

print one.a

print id(one)

print id(two)

print one == two

print one is two

one.x = 1

print one.x

print two.x

執行結果

ssh: -u /home/wfq/ops/test/singleton.py

3140279451387536

140279451387536

true

true11

process finished with exit code 0

python裝飾器實現單例模式

基本思想為 1 在裝飾器中新增乙個字典型別的自由變數 instance 2 在閉包中判斷類名是否存在於 instance中,如果不存在則建立乙個類的事例,並講其新增到字典中 如果存在則不進行例項化,直接返回字典中的例項 def singleton cls instance def singleton...

裝飾器實現單例模式

用裝飾器實現單例模式,應該算乙個很不錯的例子。我們知道,python中裝飾器無非是對物件的重新包裝,這個物件可以是函式,也可以是乙個類 decorate def test 相當於 test decorate test def decorate func def wrap args,kwargs re...

python使用裝飾器實現單例模式

直接上 第一種使用函式裝飾器實現並且使用鎖保證執行緒安全 不使用鎖實現 def singleinstance cls def new cls,args,kwargs if not hasattr cls,instance cls.instance object.new cls return cls....