FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
python-patterns/flyweight.py at master · lockys/python-patterns · GitHub
lockys
/
python-patterns
Public
forked from
faif/python-patterns
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
python-patterns
/
flyweight.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
42 lines (31 loc) · 1.05 KB
Breadcrumbs
python-patterns
/
flyweight.py
Copy path
File metadata and controls
42 lines (31 loc) · 1.05 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""http://codesnipers.com/?q=python-flyweights"""
import
weakref
class
Card
(
object
):
"""The object pool. Has builtin reference counting"""
_CardPool
=
weakref
.
WeakValueDictionary
()
"""Flyweight implementation. If the object exists in the
pool just return it (instead of creating a new one)"""
def
__new__
(
cls
,
value
,
suit
):
obj
=
Card
.
_CardPool
.
get
(
value
+
suit
,
None
)
if
not
obj
:
obj
=
object
.
__new__
(
cls
)
Card
.
_CardPool
[
value
+
suit
]
=
obj
obj
.
value
,
obj
.
suit
=
value
,
suit
return
obj
# def __init__(self, value, suit):
# self.value, self.suit = value, suit
def
__repr__
(
self
):
return
"<Card: %s%s>"
%
(
self
.
value
,
self
.
suit
)
if
__name__
==
'__main__'
:
# comment __new__ and uncomment __init__ to see the difference
c1
=
Card
(
'9'
,
'h'
)
c2
=
Card
(
'9'
,
'h'
)
print
(
c1
,
c2
)
print
(
c1
==
c2
)
print
(
id
(
c1
),
id
(
c2
))
### OUTPUT ###
# <Card: 9h> <Card: 9h>
# True
# 140368617673296 140368617673296
Back
|
FazBrowse Home
|
New Git URL