-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass
More file actions
261 lines (208 loc) · 6.72 KB
/
class
File metadata and controls
261 lines (208 loc) · 6.72 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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
1.from types import MethodType
MethodType(method,class object)
explain:
bind method to instance of class, only this instance owns method.
2.class.method=methodDefined
explain:
bind method to class, all instances have this method.
3.__slots__ = ('a','b',....)
explain:
restrict the propertys of class, can only have a,b,... of ()
warning: this __slots__ does not affect child class.
if child class has __slots__ too, it will take __slots__ of parent too.
4.class Student(object):
name = 'Student'
>>> s = Student() # 创建实例s
>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print(Student.name) # 打印类的name属性
Student
>>> s.name = 'Michael' # 给实例绑定name属性
>>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Michael
>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
Student
>>> del s.name # 如果删除实例的name属性
>>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student
explain:
property of class and property of instance of class are different and separate.
5.@property and @name.setter
class Screen(object):
@property
def width(self):
return self._width
@width.setter
def width(self,value):
if not isinstance(value,(int,float)):
raise ValueError('width must be number')
self._width=value
@property
def height(self):
return self._height
@height.setter
def height(self,value):
if not isinstance(value,(int,float)):
raise ValueError('height must be number')
self._height=height
@property
def resolution(self):
return self._width*self._height
explain:
@property is getter, and it takes another property setter with format of name.setter
6.multiple inheritance
7.MixIn
network service class:TCPServer, UDPServer
multiple process and multiple thread:ForkingMixIn, ThreadingMixIn
multiple process TCP server:
class MyTCPServer(TCPServer, ForkingMixIn):
pass
multiple threads UDP server:
class MyUDPServer(UDPServer, ThreadingMixIn):
pass
8.__str__ and __repr__
class s(object):
pass
s1=s()
print(s1) will invoke print(s1.__str__())
s1 will invoke s1.__repr__()
__iter__
class Fib(object):
def __init__(self):
self.a, self.b=0,1
def __iter(self):
return self
def __next__(self):
self.a, self.b=self.b,self.a+self.b
if self.a>100000:
raise StopIteration()
return self.a
for n in Fib():
print(n)
output:
1
1
2
3
....
46368
75025
__getitem__
make instance can be used like list.
class Fib(object):
def __getitem__(self,n):
a,b=1,1
for x in range(n):
a,,b=b,a+b
return a
f=Fib()
f[0] get 1
f[1] get 1
f[2] get 2
f[3] get 3
f[10] get 89
for slice
class Fib(object):
def __getitem__(self,n):
if isinstance(n,int):
a,b=1,1
for x in range(n):
a,b=b,a+b
return a
if isinstance(n,slice):
start=n.start
stop=n.stop
if start is None:
start=0
a,b=1,1
L=[]
for x in range(stop):
if x>=start:
L.append(a)
a,b=b,a+b
return L
9.enum
from enum import Enum
Month=Enum('M',('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'))
for name,member in Month.__members__.items():
print(name,'=>',member,','member.value)
Jan => M.Jan , 1
Feb => M.Feb , 2
Mar => M.Mar , 3
Apr => M.Apr , 4
May => M.May , 5
Jun => M.Jun , 6
Jul => M.Jul , 7
Aug => M.Aug , 8
Sep => M.Sep , 9
Oct => M.Oct , 10
Nov => M.Nov , 11
Dec => M.Dec , 12
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
Weekday(0) => Weekday.Sun
Weekday(1) => Weekday.Mon
...
Weekday(6) => Weekday.Sat
name: Sun, Mon, Tue,...
member: Weekday.Sun, Weekday.Mon,...
value: Weekday.Sun.value(0),.....
10.metaclass
class Field(object):
def __init__(self,name,column_type):
self.name=name
self.column_type=column_type
def __str__(self):
return '<%s:%s>' % (self.__class__.__name__,self.name)
class StringField(Field):
def __init__(self,name):
super(StringField,self).__init__(name,'varchar(100)')
class IntergerField(Field):
def __init__(self,name):
super(IntergerField,self).__init__(name,'bigint')
class ModelMetaclass(type):
def __new__(cls,name,bases,attrs):
if name=='Model':
return type.__new__(cls,name,bases,attrs)
print('Found model: %s' % name)
mappings=dict()
for k,v in attrs.items():
if isinstance(v,Field):
print('Found mapping: %s ==> %s' % (k,v))
mappings[k]=v
for k in mappings.keys():
attrs.pop(k)
attrs['__mappings__']=mappings
attrs['__table--']=name
return type.__new__(cls,name,bases,attrs)
class Model(dict,metaclass=ModelMetaclass):
def __init__(self,**kw):
super(Model,self).__init__(**kw)
def __getattr__(self,key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Model' object has no attribute '%s'" % key)
def __setattr__(self,key,value):
self[key]=value
def save(self):
fields=[]
params=[]
args=[]
for k,v in self.__mappings__.items():
fields.append(v.name)
params.append('?')
args.append(getarrt(self,k,None))
sql='insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))
print('SQL: %s' % sql)
print('ARGS: %s' % str(args))
u = User(id=12345, name='Michael', email='[email protected]', password='my-pwd')
u.save()