forked from xuxiaodong/using-cli
-
Notifications
You must be signed in to change notification settings - Fork 95
/
index.html
executable file
·1474 lines (1409 loc) · 33.5 KB
/
index.html
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>python高级编程</title>
<link rel="stylesheet" href="css/default.css" media="screen">
</head>
<body>
<textarea id="source">
class: middle, inverse, center
```
_ _ -
_ __ _ _| |_| |__ ___ _ __
| '_ \| | | | __| '_ \ / _ \| '_ \
| |_) | |_| | |_| | | | (_) | | | |
| .__/ \__, |\__|_| |_|\___/|_| |_|
|_| |___/ _
```
# 高级编程
### Dongweiming
2014.4.2
---
class: middle, inverse, center
## XX不理解python竟然没有end....
---
class: inverse
### 其实 可以有...
```
__builtins__.end = None
def test(x):
if x > 0:
print "a"
else:
print "b"
end
end
def main():
test(1)
print('I can use end!')
end
```
---
class: inverse
## 设置全局变量
```
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> d = {'a': 1, 'b':2}
>>> # 粗暴的写法
>>> for k, v in d.iteritems():
... exec "{}={}".format(k, v)
...
>>> # 文艺的写法
>>> globals().update(d)
>>> a, b
(1, 2)
>>> 'a', 'b'
('a', 'b')
>>> globals()['a'] = 'b'
>>> a
'b'
```
---
class: inverse
## 字符串格式化
```
>>> "{key}={value}".format(key="a", value=10) # 使⽤命名参数
'a=10'
>>> "[{0:<10}], [{0:^10}], [{0:*>10}]".format("a") # 左中右对⻬
'[a ], [ a ], [*********a]'
>>> "{0.platform}".format(sys) # 成员
'darwin'
>>> "{0[a]}".format(dict(a=10, b=20)) # 字典
'10'
>>> "{0[5]}".format(range(10)) # 列表
'5'
>>> "My name is {0} :-{{}}".format('Fred') # 真得想显示{},需要双{}
'My name is Fred :-{}'
>>> "{0!r:20}".format("Hello")
"'Hello' "
>>> "{0!s:20}".format("Hello")
'Hello '
>>> "Today is: {0:%a %b %d %H:%M:%S %Y}".format(datetime.now())
'Today is: Mon Mar 31 23:59:34 2014'
```
([PEP3101](http://legacy.python.org/dev/peps/pep-3101/))
---
class: inverse
## 列表去重
```
>>> l = [1, 2, 2, 3, 3, 3]
>>> {}.fromkeys(l).keys()
[1, 2, 3] # 列表去重(1)
>>> list(set(l)) # 列表去重(2)
[1, 2, 3]
In [2]: %timeit list(set(l))
1000000 loops, best of 3: 956 ns per loop
In [3]: %timeit {}.fromkeys(l).keys()
1000000 loops, best of 3: 1.1 µs per loop
In [4]: l = [random.randint(1, 50) for i in range(10000)]
In [5]: %timeit list(set(l))
1000 loops, best of 3: 271 µs per loop
In [6]: %timeit {}.fromkeys(l).keys()
1000 loops, best of 3: 310 µs per loop
PS: 在字典较大的情况下, 列表去重(1)略慢了
```
---
class: inverse
## 操作字典
```
>>> dict((["a", 1], ["b", 2])) # ⽤两个序列类型构造字典
{'a': 1, 'b': 2}
>>> dict(zip("ab", range(2)))
{'a': 0, 'b': 1}
>>> dict(map(None, "abc", range(2)))
{'a': 0, 'c': None, 'b': 1}
>>> dict.fromkeys("abc", 1) # ⽤序列做 key,并提供默认 value
{'a': 1, 'c': 1, 'b': 1}
>>> {k:v for k, v in zip("abc", range(3))} # 字典解析
{'a': 0, 'c': 2, 'b': 1}
>>> d = {"a":1, "b":2}
>>> d.setdefault("a", 100) # key 存在,直接返回 value
1
>>> d.setdefault("c", 200) # key 不存在,先设置,后返回
200
>>> d
{'a': 1, 'c': 200, 'b': 2}
```
---
class: inverse
## 字典视图
```
>>> d1 = dict(a = 1, b = 2)
>>> d2 = dict(b = 2, c = 3)
>>> d1 & d2 # 字典不⽀支持该操作
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'dict' and 'dict'
>>> v1 = d1.viewitems()
>>> v2 = d2.viewitems()
>>> v1 & v2 # 交集
set([('b', 2)])
>>> dict(v1 & v2) # 可以转化为字典
{'b': 2}
>>> v1 | v2 # 并集
set([('a', 1), ('b', 2), ('c', 3)])
>>> v1 - v2 #差集(仅v1有,v2没有的)
set([('a', 1)])
>>> v1 ^ v2 # 对称差集 (不会同时出现在 v1 和 v2 中)
set([('a', 1), ('c', 3)])
>>> ('a', 1) in v1 #判断
True
```
---
class: inverse
## vars
```
>>> vars() is locals()
True
>>> vars(sys) is sys.__dict__
True
```
---
class: inverse
### from \_\_future\_\_ import unicode_literals
```
>>> s = '美的'
>>> s
'\xe7\xbe\x8e\xe7\x9a\x84'
>>> from __future__ import unicode_literals
>>> s = '美的'
>>> s
u'\u7f8e\u7684'
>>> s.encode('utf-8')
'\xe7\xbe\x8e\xe7\x9a\x84'
>>> s = b'美的'
>>> s
'\xe7\xbe\x8e\xe7\x9a\x84'
>>> type(s)
<type 'str'>
```
---
class: inverse
### from \_\_future\_\_ import absolute_import
### 不是支持了绝对引入,而是拒绝隐式引入
```
$cat for_absolute_import/string.py
a = 1
$cat for_absolute_import/main.py
import string # 其实我们要的是当前目录下的string模块
>>> from for_absolute_import.main import string
>>> string # 是隐式引入的
<module 'for_absolute_import.string' from 'for_absolute_import/string.py'>
>>> 1
1
## 我来修改下
$cat for_absolute_import/main.py
from __future__ import absolute_import
import string
>>> from for_absolute_import.main import string
>>> string # 看这里其实还是在用string模块
<module 'string' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/string.pyc'>
```
---
class: inverse
## 我靠,我的需求呢? -- 在很多开源项目是拒绝你的隐式用法的,
## 比如celery
## 来点标准做法:
```
from __future__ import absolute_import
from .string import a # 比较常用的风格
from for_absolute_import.string import a \
# 官方推荐的风格,强烈建议这样的风格
```
---
class: inverse
## 一个关于编码的问题
```
$cat encoding_example.py
# encoding: utf-8
name = 'helló wörld from example'
$cat encoding.py
# encoding: utf-8
from __future__ import unicode_literals
import encoding_example as a
b = 'helló wörld from this'
print b + a.name
$python encoding.py
Traceback (most recent call last):
File "encoding.py", line 6, in <module>
print b + a.name
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3
in position 4: ordinal not in range(128)
```
---
class: inverse
## 原因是: encoding_example里面没有对文字自动转化为unicode,默认是ascii编码
```
$cat encoding.py
# encoding: utf-8
>>> from __future__ import unicode_literals
>>> import encoding_example as a
>>> b = 'helló wörld from this'
>>> print b + a.name.decode('utf-8')
helló wörld from thishelló wörld from example
>>> # 或者这样用:
>>> print b.encode('utf-8') + a.name
helló wörld from thishelló wörld from example
```
---
class: inverse
## super 当子类调用父类属性时一般的做法是这样
```
>>> class LoggingDict(dict):
... def __setitem__(self, key, value):
... print('Setting {0} to {1}'.format(key, value))
... dict.__setitem__(key, value)
```
### 问题是假如你继承的不是dict而是其他,那么就要修改2处,其实可以这样
```
>>> class LoggingDict(dict):
... def __setitem__(self, key, value):
... print('Setting {0} to {1}'.format(key, value))
... super(LoggingDict, self).__setitem__(key, value)
```
### PS: 感觉super自动找到了LoggingDict的父类(dict),然后把self转化为其实例
---
class: inverse
## 手写一个迭代器
```
>>> class Data(object):
... def __init__(self):
... self._data = []
... def add(self, x):
... self._data.append(x)
... def data(self):
... return iter(self._data)
...
>>> d = Data()
>>> d.add(1)
>>> d.add(2)
>>> d.add(3)
>>> for x in d.data():
... print(x)
...
1
2
3
```
---
class: inverse
## 标准迭代器
```
>>> class Data(object):
... def __init__(self, *args):
... self._data = list(args)
... self._index = 0
... def __iter__(self):
... return self
... # 兼容python3
... def __next__(self):
... return self.next()
... def next(self):
... if self._index >= len(self._data):
... raise StopIteration()
... d = self._data[self._index]
... self._index += 1
... return d
...
>>> d = Data(1, 2, 3)
>>> for x in d:
... print(x)
...
1
2
3
>>> d = Data(1, 2, 3)
>>> it = iter(d)
>>> next(it)
1
>>> next(it)
2
```
---
class: inverse
## 生成器
```
>>> class Data(object):
... def __init__(self, *args):
... self._data = list(args)
... def __iter__(self):
... for x in self._data:
... yield x
...
>>> d = Data(1, 2, 3)
>>> for x in d:
... print(x)
...
1
2
3
>>> (i for i in [1,2,3]) # 这是生成器表达式
<generator object <genexpr> at 0x10657a640>
```
---
class: inverse
## 斐波那契数列
```
>>> import itertools
>>>
>>> def fib():
... a, b = 0, 1
... while 1:
... yield b
... a, b = b, a + b
...
>>>
>>> print list(itertools.islice(fib(), 10))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
```
---
class: inverse
## 其实yield和协程关系很密切
```
>>> def coroutine():
... print "coroutine start..."
... result = None
... while True:
... s = yield result
... result = 'result: {}'.format(s)
...
>>> c = coroutine() # 函数返回协程对象
>>> c.send(None) # 使用 send(None) 或 next() 启动协程
coroutine start...
>>> c.send("first") # 向协程发送消息,使其恢复执⾏
'result: first'
>>> c.send("second")
'result: second'
>>> c.close() # 关闭协程,使其退出。或⽤c.throw() 使其引发异常
>>> c.send("never recv")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
```
---
class: inverse
## 来个回调(阻塞的)
```
>>> def framework(logic, callback):
... s = logic()
... print "[FX] logic: ", s
... print "[FX] do something"
... callback("async: " + s)
...
>>> def logic():
... s = "mylogic"
... return s
...
>>> def callback(s):
... print s
...
>>> framework(logic, callback)
[FX] logic: mylogic
[FX] do something
async: mylogic
```
---
class: inverse
## 来个回调(异步的)
```
>>> def framework(logic):
... try:
... it = logic()
... s = next(it)
... print "[FX] logic: ", s
... print "[FX] do something"
... it.send("async: " + s)
... except StopIteration:
... pass
...
>>> def logic():
... s = "mylogic"
... r = yield s
... print r
...
>>> framework(logic)
[FX] logic: mylogic
[FX] do something
async: mylogic
```
---
class: inverse
## 实现一个with上下文管理类(自动关闭mongodb连接)
```
>>> import pymongo
>>> class Operation(object):
... def __init__(self, database,
... host='localhost', port=27017):
... self._db = pymongo.MongoClient(
... host, port)[database]
... def __enter__(self):
... return self._db
... def __exit__(self, exc_type, exc_val, exc_tb):
... self._db.connection.disconnect()
...
>>> with Operation(database='test') as db:
... print db.test.find_one()
...
{u'a': 0.9075717522597431, u'_id': ObjectId('52e0da5cc23e7dbdb0a1ec36')}
```
---
class: inverse
## 看到这里, 就得说说contextmanager
```
@contextlib.contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
with some_generator(<arguments>) as <variable>:
<body>
```
也就是:
```
<setup>
try:
<variable> = <value>
<body>
finally:
<cleanup>
```
---
class: inverse
## contextmanager例子(一)
```
>>> lock = threading.Lock()
>>> @contextmanager
... def openlock():
... print('Acquire')
... lock.acquire()
... yield
... print('Releasing')
... lock.release()
...
>>> with openlock():
... print('Lock is locked: {}'.format(lock.locked()))
... print 'Do some stuff'
...
Acquire
Lock is locked: True
Do some stuff
Releasing
```
---
class: inverse
## contextmanager例子(二)
```
>>> @contextmanager
... def openlock2():
... print('Acquire')
... with lock: # threading.Lock其实就是个with的上下文管理器.
... # __enter__ = acquire
... yield
... print('Releasing')
...
>>> with openlock2():
... print('Lock is locked: {}'.format(lock.locked()))
... print 'Do some stuff'
...
Acquire
Lock is locked: True
Do some stuff
Releasing
```
---
class: inverse
## contextmanager例子(三)
```
>>> @contextmanager
... def operation(database, host='localhost',
port=27017):
... db = pymongo.MongoClient(host, port)[database]
... yield db
... db.connection.disconnect()
...
>>> import pymongo
>>> with operation('test') as db:
... print(db.test.find_one())
...
{u'a': 0.9075717522597431, u'_id': ObjectId('52e0da5cc23e7dbdb0a1ec36')}
```
---
class: inverse
## 包导入
```
>>> import imp
>>> f, filename, description = imp.find_module('sys')
>>> sys = imp.load_module('sys', f, filename, description)
>>> sys
<module 'sys' (built-in)>
>>> os = __import__('os')
>>> os.path
<module 'posixpath' from '/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.pyc'>
>>> filename = "t.py"
>>> f = open("t.py")
>>> description = ('.py', 'U', 1)
>>> t = imp.load_module('some', f, filename, description) # t就是`import t`后的结果
```
---
class: inverse
## 包构建\_\_all\_\_
```
因为 import 实际导⼊的是⺫标模块 globals 名字空间中的成员,
那么就有⼀个问题: 模块也会导⼊其他模块,这些模块同样在⺫标模块
的名字空间中. "import *" 操作时,所有这些一并被带入到当前模
块中,造成一定程度的污染
__all__ = ["add", "x"]
```
---
class: inverse
## 包构建\_\_path\_\_
```
某些时候,包内的文件太多,需要分类存放到多个目录中,但⼜不想拆分
成新的包或⼦包。这么做是允许的, 只要在 __init__.py 中⽤
__path__ 指定所有⼦目录的全路径即可 (⼦目录可放在包外)
<dir>
|_ __init__.py
|
|_ a <dir>
. |_ add.py
|
|_ b <dir>
|_ sub.py
from os.path import abspath, join
subdirs = lambda *dirs: [abspath(
join(__path__[0], sub)) for sub in dirs]
__path__ = subdirs("a", "b")
```
---
class: inverse
## 静态方法和类方法的区别
```
>>> class User(object):
... def a(self):
... print 'a'
... @staticmethod
... def b():
... print 'b'
... @classmethod
... def c(cls):
... print 'c'
>>> u = User()
>>> u.a(), u.b(), u.c()
(a, b, c)
>>> User.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method a() must be called with User instance as first argument (got nothing instead)
>>> User.b()
b
>>> User.c()
c
```
---
class: inverse
## 静态方法和类方法的区别其实是在这里
```
>>> class User(object):
... a = 1
... @staticmethod
... def b():
... print self.a
... @classmethod
... def c(cls):
... print cls.a
>>> u = User()
>>> u.b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in b
NameError: global name 'self' is not defined
>>> User.b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in b
NameError: global name 'self' is not defined
>>> u.c(), User.c()
(1, 1)
```
---
class: inverse
## \_\_slots\_\_ 大量属性时减少内存占用
```
>>> class User(object):
... __slots__ = ("name", "age")
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
>>> u = User("Dong", 28)
>>> hasattr(u, "__dict__")
False
>>> u.title = "xxx"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'User' object has no attribute 'title'
```
---
class: inverse
## Packaging Tools的未来
### "./setup.py install must die"
### pip > 1.6已经消除pip对setuptools的依赖
![History](img/pypa.png)
### [Warehouse-Next Generation Python Package Repository](https://warehouse.readthedocs.org/)
### [Demo-server](https://pypi-preview.a.ssl.fastly.net/)
---
class: inverse
## wheel(即将替代Eggs的二进制包格式)的优点
### 1. 有官方的PEP427支持
### 2. 打包后不包含pyc文件
### 3. 一个wheel包可以提供多python版本标签甚至系统架构
---
class: inverse
## 装饰器
### 普通装饰器
```
>>> def common(func):
... def _deco(*args, **kwargs):
... print 'args:', args
... return func(*args, **kwargs)
... return _deco
...
>>> @common
... def test(p):
... print p
...
>>> test
<function _deco at 0x10d996a28>
>>> test(1)
args: (1,)
1
```
---
class: inverse
## 装饰器
### 给函数的类装饰器(避免在装饰器对象上保留状态)
```
>>> class Common(object):
... def __init__(self, func):
... self.func = func
... def __call__(self, *args, **kwargs):
... print 'args:', args
... return self.func(*args, **kwargs)
...
>>>
>>> @Common
... def test(p):
... print p
...
>>> test
<__main__.Common object at 0x10d99bf50>
>>> test(1)
args: (1,)
1
```
---
class: inverse
## 装饰器
### 给类的函数装饰器
```
>>> def borg(cls):
... cls._state = {}
... orig_init = cls.__init__
... def new_init(self, *args, **kwargs):
... self.__dict__ = cls._state
... orig_init(self, *args, **kwargs)
... cls.__init__ = new_init
... return cls
>>> @borg
... class A(object):
... def common(self):
... print hex(id(self))
>>> a, b = A(), A()
>>> b.d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'd'
>>> a.d = 1
>>> b.d
1
```
---
class: inverse
## 装饰器
### 带参数的装饰器
```
>>> def common(*args, **kw):
... a = args
... def _common(func):
... def _deco(*args, **kwargs):
... print 'args:', args, a
... return func(*args, **kwargs)
... return _deco
... return _common
...
>>> @common('c')
... def test(p):
... print p
...
>>> test
<function _deco at 0x10d99e5f0>
>>> test(1)
args: (1,) ('c',)
1
```
---
class: inverse
## @property
```
>>> class C(object):
... def __init__(self):
... self._x = None
... def getx(self):
... print 'get x'
... return self._x
... def setx(self, value):
... print 'set x'
... self._x = value
... def delx(self):
... print 'del x'
... del self._x
... x = property(getx, setx, delx, "I'm the 'x' property.")
...
>>> c = C()
>>> c.x = 12
set x
>>> c.x
get x
12
>>> del c.x
del x
```
---
class: inverse
## @property的另外使用方法
```
>>> class Parrot(object):
... def __init__(self):
... self._voltage = 100000
... @property
... def voltage(self):
... """Get the current voltage."""
... return self._voltage
... @voltage.setter
... def voltage(self, value):
... """Set to current voltage."""
... self._voltage = value
...
>>> c = Parrot()
>>> c.voltage
100000
>>> c.voltage = 200
>>> c.voltage
200
```
---
class: inverse
## 描述符
###1. 当希望对某些类的属性进行特别的处理而不会对整体的其他属性有影响的话,可以使用描述符
###2. 只要一个类实现了\_\_get\_\_、\_\_set\_\_、\_\_delete\_\_方法就是描述符
###3. 描述符会"劫持"那些本对于self.\_\_dict\_\_的操作
###4. 把一个类的操作托付与另外一个类
###5. 静态方法, 类方法, property都是构建描述符的类
---
class: inverse
## 描述符的例子
```
>>> class MyDescriptor(object):
... _value = ''
... def __get__(self, instance, klass):
... return self._value
... def __set__(self, instance, value):
... self._value = value.swapcase()
>>> class Swap(object):
... swap = MyDescriptor()
>>> instance = Swap()
>>> instance.swap
''
>>> # 对swap的属性访问被描述符类重载了
>>> instance.swap = 'make it swap'
>>> instance.swap
'MAKE IT SWAP'
>>> instance.__dict__ # 没有用到__dict__:被劫持了
{}
```
---
class: inverse
## 深入描述符
```
>>> def t(): # 随便定义个函数(或者lambda匿名函数)
... pass
...
>>> dir(t)
['__call__', '__class__', '__closure__', '__code__',
'__defaults__', '__delattr__', '__dict__', '__doc__',
'__format__', '__get__', '__getattribute__', '__globals__',
'__hash__', '__init__', '__module__', '__name__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'func_closure',
'func_code', 'func_defaults', 'func_dict', 'func_doc',
'func_globals', 'func_name']
注意: **t有__get__方法.**
总结: 所有 Python 函数都默认是一个描述符.
这个描述符的特性在"类"这一对象上下文之外没有任何意义,
但只要到了类中:
instance.swap变成了:
Swap.__dict__['swap'].__get__(instance, Swap)
```
---
class: inverse
## 一个开源实现
```
>>> class cached_property(object):
... # from werkzeug.utils import cached_property
... def __init__(self, func, name=None, doc=None):
... self.__name__ = name or func.__name__
... self.__module__ = func.__module__
... self.__doc__ = doc or func.__doc__
... self.func = func
... def __get__(self, obj, type=None):
... if obj is None:
... return self
... value = obj.__dict__.get(self.__name__, _missing)
... if value is _missing:
... value = self.func(obj)
... obj.__dict__[self.__name__] = value
... return value
```
---
class: inverse
## 用python实现静态方法和类方法
```
>>> class myStaticMethod(object):
... def __init__(self, method):
... self.staticmethod = method
... def __get__(self, object, type=None):
... return self.staticmethod
...
>>> class myClassMethod(object):
... def __init__(self, method):
... self.classmethod = method
... def __get__(self, object, klass=None):
... if klass is None:
... klass = type(object)
... def newfunc(*args):
... return self.classmethod(klass, *args)
... return newfunc
```
---
class: center, middle, inverse
# 元类......
## Metaclasses
---
class: inverse
## 元类是什么
### 对象是类的实例,类是它的元类的实例
```
>>> class Myclass(): pass # 不要学我的写法
>>> type(Myclass)
<type 'classobj'>
>>> class Myclass(object): pass
>>> type(Myclass)
<type 'type'>
>>> type(type)
<type 'type'>
>>> class Myclass: # 对于这个例子,有没有括号都无所谓
... __metaclass__ = type
>>> type(Myclass)
<type 'type'>
>>> print Myclass
<class '__main__.Myclass'>
>>> print Myclass()
<__main__.Myclass object at 0x10d9ad190>
```
---
class: inverse
## 模拟生成一个类
```
>>> def __init__(self, func):
... self.func = func
>>> def hello(self):
... print 'hello world'
>>> attrs = {'__init__': __init__, 'hello': hello}
>>> bases = (object,)
>>> Hello = type('Hello', bases, attrs)
>>> h = Hello(lambda a, b=3: a + b)
>>> h.hello()
hello world
# 其实等于下面的类
class Hello(object):
def __init__(self, func):
self.func = func
def hello(self):
print 'hello world'
```
---
class: inverse