Skip to content

Commit c6003fc

Browse files
committed
Add some example
1 parent 8bdb1ba commit c6003fc

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

8.25.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# coding: utf-8
2+
3+
from __future__ import print_function
4+
import weakref
5+
6+
class Spam:
7+
8+
def __init__(self, name):
9+
self.name = name
10+
11+
def __str__(self):
12+
return self.name
13+
14+
_span_cache = weakref.WeakValueDictionary()
15+
def get_spam(name):
16+
if name in _span_cache:
17+
return _span_cache[name]
18+
else:
19+
spam = Spam(name)
20+
_span_cache[name] = spam
21+
return spam
22+
23+
a = get_spam('foo')
24+
b = get_spam('bar')
25+
print(_span_cache.items())

9.1.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# coding: utf-8
2+
3+
from __future__ import print_function
4+
import time
5+
from functools import wraps
6+
7+
8+
def timethis(func):
9+
@wraps(func)
10+
def wrapper(*args, **kwargs):
11+
start = time.time()
12+
result = func(*args, **kwargs)
13+
end = time.time()
14+
print(end - start)
15+
return wrapper
16+
17+
@timethis
18+
def test():
19+
time.sleep(1)
20+
21+
print(test.__name__)
22+
print(dir(test))
23+
print(test.__wrapped__)
24+
test()

9.13.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# coding: utf-8
2+
3+
4+
class Singleton(type):
5+
def __init__(self, *args, **kwargs):
6+
self.__instance = None
7+
super(Singleton, self).__init__(*args, **kwargs)
8+
9+
def __call__(self, *args, **kwargs):
10+
if self.__instance is None:
11+
self.__instance = super(Singleton, self).__call__(*args, **kwargs)
12+
return self.__instance
13+
else:
14+
return self.__instance
15+
16+
17+
class Spam():
18+
__metaclass__ = Singleton
19+
def __init__(self):
20+
print('Creating Spam')
21+
22+
23+
a = Spam()
24+
b = Spam()
25+
26+
print a is b

0 commit comments

Comments
 (0)