3
3
Singleton
4
4
"""
5
5
6
- class Singleton (type ):
6
+
7
+ class Singleton1 (type ):
7
8
_instance = None
8
9
9
10
def __call__ (cls , * args , ** kwargs ):
@@ -12,36 +13,36 @@ def __call__(cls, *args, **kwargs):
12
13
return cls ._instance
13
14
14
15
15
- class Singleton (type ):
16
+ class Singleton2 (type ):
16
17
"""
17
18
Singleton metaclass
18
19
Based on Python Cookbook 3rd Edition Recipe 9.13
19
20
Only one instance of a class can exist. Does not work with __slots__
20
21
"""
21
22
22
23
def __init__ (self , * args , ** kw ):
23
- super (Singleton , self ).__init__ (* args , ** kw )
24
+ super (Singleton2 , self ).__init__ (* args , ** kw )
24
25
self .__instance = None
25
26
26
27
def __call__ (self , * args , ** kw ):
27
28
if self .__instance is None :
28
- self .__instance = super (Singleton , self ).__call__ (* args , ** kw )
29
+ self .__instance = super (Singleton2 , self ).__call__ (* args , ** kw )
29
30
return self .__instance
30
31
31
-
32
32
33
-
34
- class DB (metaclass = Singleton ):
33
+ class DBMongo (metaclass = Singleton2 ):
34
+ pass
35
+
36
+ class DBPostgres (metaclass = Singleton2 ):
35
37
pass
36
38
37
39
38
40
if __name__ == '__main__' :
39
- s1 = DB ()
40
- s2 = DB ()
41
- s3 = DB ()
41
+ m1 = DBMongo ()
42
+ m2 = DBMongo ()
42
43
43
- print (id (s1 ))
44
- print (id (s2 ))
45
- print (id (s3 ))
44
+ p1 = DBPostgres ()
45
+ p2 = DBPostgres ()
46
46
47
- print (id (s1 ) == id (s2 ) == id (s3 ))
47
+ print (f"Mongo: { id (m1 )} - { id (m2 )} " , id (m1 ) == id (m2 ))
48
+ print (f"Postgres: { id (p1 )} - { id (p2 )} " , id (p1 ) == id (p2 ))
0 commit comments