FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Design-Patterns-in-Python/singleton.py at master · coder-zh/Design-Patterns-in-Python · GitHub
coder-zh
/
Design-Patterns-in-Python
Public
forked from
gennad/Design-Patterns-in-Python
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
Design-Patterns-in-Python
/
singleton.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (36 loc) · 1.03 KB
Breadcrumbs
Design-Patterns-in-Python
/
singleton.py
Copy path
File metadata and controls
48 lines (36 loc) · 1.03 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
37
38
39
40
41
42
43
44
45
46
47
48
# ---------- Singletone ----------
# Real Singleton instance
class
Singleton
(
object
):
def
__new__
(
type
):
if
not
'_the_instance'
in
type
.
__dict__
:
type
.
_the_instance
=
object
.
__new__
(
type
)
return
type
.
_the_instance
a
=
Singleton
()
a
.
toto
=
12
b
=
Singleton
()
print
b
.
toto
print
id
(
a
),
id
(
b
)
# The same !!
# ---------- Borg's singletone ----------
class
Borg
:
__shared_state
=
{}
def
__init__
(
self
):
self
.
__dict__
=
self
.
__shared_state
a
=
Borg
()
a
.
toto
=
12
b
=
Borg
()
print
b
.
toto
print
id
(
a
),
id
(
b
)
# different ! but states are sames
# ---------- Alex's Martelli examples ----------
class
Singleton
(
object
):
def
__new__
(
cls
,
*
a
,
**
k
):
if
not
hasattr
(
cls
,
'_inst'
):
cls
.
_inst
=
super
(
Singleton
,
cls
).
__new__
(
cls
,
*
a
,
**
k
)
return
cls
.
_inst
class
Borg
(
object
):
"""Subclassing is no problem."""
_shared_state
=
{}
def
__new__
(
cls
,
*
a
,
**
k
):
obj
=
super
(
Borg
,
cls
).
__new__
(
cls
,
*
a
,
**
k
)
obj
.
__dict__
=
cls
.
_shared_state
return
obj
Back
|
FazBrowse Home
|
New Git URL