-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode-examples.py
More file actions
169 lines (119 loc) · 3.04 KB
/
code-examples.py
File metadata and controls
169 lines (119 loc) · 3.04 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# --------------------------------
# 1. Context Manager
# --------------------------------
import sqlite3
class DataConn:
"""Manager for connecting to a database"""
def __init__(self, db_name):
self.db_name = db_name
def __enter__(self):
"""Open a database connection"""
self.conn = sqlite3.connect(self.db_name)
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
"""Close the connection"""
self.conn.close()
if exc_val:
"""Handle closing error"""
raise
if __name__ == '__main__':
db = 'test.db'
with DataConn(db) as conn:
cursor = conn.cursor()
# --------------------------------
# 2. Singleton
# --------------------------------
# Main idea:
# 1. Ensures that a class has only one instance.
# 2. Provides a global access point.
class Singleton(object):
def __new__(cls):
# Override object creation
if not hasattr(cls, 'instance'):
cls.instance = super(Singleton, cls).__new__(cls)
return cls.instance
s = Singleton()
print(id(s))
print(s)
b = Singleton()
print(id(b))
print(b)
print(s is b)
# Output:
# 140425907838864
# <__main__.Singleton object at 0x7fb7745a9f90>
# 140425907838864
# <__main__.Singleton object at 0x7fb7745a9f90>
# True
# --------------------------------
# 3. Iterator
# --------------------------------
class SimpleIterator:
def __iter__(self):
# Return the iterator to use in a for loop
return self
def __init__(self, limit):
self.limit = limit
self.counter = 0
def __next__(self):
if self.counter < self.limit:
self.counter += 1
return self.counter
else:
raise StopIteration
iter = SimpleIterator(5)
for i in iter:
print(i)
# --------------------------------
# 4. Generator
# --------------------------------
# A function that contains `yield` returns a generator object
# instead of executing immediately.
# It runs each time the `__next__()` method is called.
# In a `for` loop, this happens automatically.
# The function preserves variable values between calls.
def gen(n):
for i in range(n):
yield i + 1
g = gen(5)
next(g)
# or
for n in gen(5):
print(n)
# --------------------------------
# 5. Decorator
# --------------------------------
# Decorators are “wrappers” that allow changing
# a function’s behavior without modifying its code.
def decorator(func):
def wrapper_func():
print('hello')
func()
return wrapper_func
def func1():
print('world')
# or
@decorator
def func2():
print('world')
decorator(func1)()
# or
func2()
# >> hello
# >> world
# --------------------------------
# 6. Decorator with parameters
# --------------------------------
def param_decorator(word):
def decorator(func):
def wrapper_func():
print('hello')
func()
return wrapper_func
return decorator
@param_decorator('hello')
def func3():
print('world')
func3()
# >> hello
# >> world