forked from lymin/python_interview_question
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path80.py
More file actions
36 lines (29 loc) · 656 Bytes
/
80.py
File metadata and controls
36 lines (29 loc) · 656 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
36
# 使用new关键字实现
class A(object):
__instance = None
def __new__(cls, *args, **kwargs):
if cls.__instance is None:
cls.__instance = object.__new__(cls)
return cls.__instance
else:
return cls.__instance
def __init__(self):
pass
A1 = A()
A2 = A()
print(id(A1) == id(A2))
# 使用装饰器
def singleton(cls):
__instance = {}
def inner():
if cls not in __instance:
__instance[cls] = cls()
return __instance[cls]
return inner
@singleton
class B(object):
def __init__(self):
pass
B1 = B()
B2 = B()
print(id(B1) == id(B2))