forked from lymin/python_interview_question
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path17.py
More file actions
35 lines (28 loc) · 678 Bytes
/
17.py
File metadata and controls
35 lines (28 loc) · 678 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 使用基类new
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton,
cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
foo1 = Foo()
foo2 = Foo()
print(foo1 is foo2)
# 使用装饰器
from functools import wraps
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class FOO(object):
pass
foo3 = FOO()
foo4 = FOO()
print(foo3 is foo4)