-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogramming.html
More file actions
1915 lines (1859 loc) · 201 KB
/
programming.html
File metadata and controls
1915 lines (1859 loc) · 201 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
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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_TW">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>程式開發常見問答集 — Python 3.7.0 說明文件</title>
<link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/translations.js"></script>
<script type="text/javascript" src="../_static/sidebar.js"></script>
<link rel="search" type="application/opensearchdescription+xml"
title="在 Python 3.7.0 說明文件 中搜尋"
href="../_static/opensearch.xml"/>
<link rel="author" title="關於這些文件" href="../about.html" />
<link rel="index" title="索引" href="../genindex.html" />
<link rel="search" title="搜尋" href="../search.html" />
<link rel="copyright" title="Copyright" href="../copyright.html" />
<link rel="next" title="Design and History FAQ" href="design.html" />
<link rel="prev" title="常見Python問答集" href="general.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/faq/programming.html" />
<script type="text/javascript" src="../_static/copybutton.js"></script>
<script type="text/javascript" src="../_static/switchers.js"></script>
</head><body>
<div class="related" role="navigation" aria-label="related navigation">
<h3>瀏覽</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">索引</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python 模組索引"
>模組</a> |</li>
<li class="right" >
<a href="design.html" title="Design and History FAQ"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="general.html" title="常見Python問答集"
accesskey="P">上一頁</a> |</li>
<li><img src="../_static/py.png" alt=""
style="vertical-align: middle; margin-top: -1px"/></li>
<li><a href="https://www.python.org/">Python</a> »</li>
<li>
<span class="language_switcher_placeholder">zh_TW</span>
<span class="version_switcher_placeholder">3.7.0</span>
<a href="../index.html">Documentation </a> »
</li>
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python 常見問題</a> »</li>
<li class="right">
<div class="inline-search" style="display: none" role="search">
<form class="inline-search" action="../search.html" method="get">
<input placeholder="Quick search" type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
<script type="text/javascript">$('.inline-search').show(0);</script>
|
</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="programming-faq">
<h1><a class="toc-backref" href="#id2">程式開發常見問答集</a><a class="headerlink" href="#programming-faq" title="本標題的永久連結">¶</a></h1>
<div class="contents topic" id="id1">
<p class="topic-title first">目錄</p>
<ul class="simple">
<li><a class="reference internal" href="#programming-faq" id="id2">程式開發常見問答集</a><ul>
<li><a class="reference internal" href="#general-questions" id="id3">常見問題</a><ul>
<li><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id4">是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器?</a></li>
<li><a class="reference internal" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" id="id5">有沒有工具幫忙找 bug或執行靜態分析</a></li>
<li><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id6">How can I create a stand-alone binary from a Python script?</a></li>
<li><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id7">Are there coding standards or a style guide for Python programs?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#core-language" id="id8">Core Language</a><ul>
<li><a class="reference internal" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" id="id9">為什麼當變數有值時我得到錯誤訊息 UnboundLocalError</a></li>
<li><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id10">Python 的區域變數和全域變數有什麼規則?</a></li>
<li><a class="reference internal" href="#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" id="id11">Why do lambdas defined in a loop with different values all return the same result?</a></li>
<li><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id12">How do I share global variables across modules?</a></li>
<li><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id13">What are the 「best practices」 for using import in a module?</a></li>
<li><a class="reference internal" href="#why-are-default-values-shared-between-objects" id="id14">Why are default values shared between objects?</a></li>
<li><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id15">How can I pass optional or keyword parameters from one function to another?</a></li>
<li><a class="reference internal" href="#what-is-the-difference-between-arguments-and-parameters" id="id16">What is the difference between arguments and parameters?</a></li>
<li><a class="reference internal" href="#why-did-changing-list-y-also-change-list-x" id="id17">Why did changing list 『y』 also change list 『x』?</a></li>
<li><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id18">How do I write a function with output parameters (call by reference)?</a></li>
<li><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id19">How do you make a higher order function in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id20">How do I copy an object in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id21">How can I find the methods or attributes of an object?</a></li>
<li><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id22">How can my code discover the name of an object?</a></li>
<li><a class="reference internal" href="#what-s-up-with-the-comma-operator-s-precedence" id="id23">What’s up with the comma operator’s precedence?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id24">Is there an equivalent of C’s 「?:」 ternary operator?</a></li>
<li><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id25">Is it possible to write obfuscated one-liners in Python?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#numbers-and-strings" id="id26">Numbers and strings</a><ul>
<li><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id27">How do I specify hexadecimal and octal integers?</a></li>
<li><a class="reference internal" href="#why-does-22-10-return-3" id="id28">Why does -22 // 10 return -3?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id29">How do I convert a string to a number?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id30">How do I convert a number to a string?</a></li>
<li><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id31">How do I modify a string in place?</a></li>
<li><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id32">How do I use strings to call functions/methods?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id33">Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?</a></li>
<li><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id34">Is there a scanf() or sscanf() equivalent?</a></li>
<li><a class="reference internal" href="#what-does-unicodedecodeerror-or-unicodeencodeerror-error-mean" id="id35">What does 『UnicodeDecodeError』 or 『UnicodeEncodeError』 error mean?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#performance" id="id36">Performance</a><ul>
<li><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id37">My program is too slow. How do I speed it up?</a></li>
<li><a class="reference internal" href="#what-is-the-most-efficient-way-to-concatenate-many-strings-together" id="id38">What is the most efficient way to concatenate many strings together?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequences-tuples-lists" id="id39">Sequences (Tuples/Lists)</a><ul>
<li><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id40">How do I convert between tuples and lists?</a></li>
<li><a class="reference internal" href="#what-s-a-negative-index" id="id41">What’s a negative index?</a></li>
<li><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id42">How do I iterate over a sequence in reverse order?</a></li>
<li><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id43">How do you remove duplicates from a list?</a></li>
<li><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id44">How do you make an array in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id45">How do I create a multidimensional list?</a></li>
<li><a class="reference internal" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" id="id46">How do I apply a method to a sequence of objects?</a></li>
<li><a class="reference internal" href="#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works" id="id47">Why does a_tuple[i] += [『item』] raise an exception when the addition works?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#dictionaries" id="id48">字典</a><ul>
<li><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id49">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id50">How can I sort one list by values from another list?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#objects" id="id51">Objects</a><ul>
<li><a class="reference internal" href="#what-is-a-class" id="id52">What is a class?</a></li>
<li><a class="reference internal" href="#what-is-a-method" id="id53">What is a method?</a></li>
<li><a class="reference internal" href="#what-is-self" id="id54">What is self?</a></li>
<li><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id55">How do I check if an object is an instance of a given class or of a subclass of it?</a></li>
<li><a class="reference internal" href="#what-is-delegation" id="id56">What is delegation?</a></li>
<li><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" id="id57">How do I call a method defined in a base class from a derived class that overrides it?</a></li>
<li><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id58">How can I organize my code to make it easier to change the base class?</a></li>
<li><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id59">How do I create static class data and static class methods?</a></li>
<li><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id60">How can I overload constructors (or methods) in Python?</a></li>
<li><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id61">I try to use __spam and I get an error about _SomeClassName__spam.</a></li>
<li><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id62">My class defines __del__ but it is not called when I delete the object.</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id63">How do I get a list of all instances of a given class?</a></li>
<li><a class="reference internal" href="#why-does-the-result-of-id-appear-to-be-not-unique" id="id64">Why does the result of <code class="docutils literal notranslate"><span class="pre">id()</span></code> appear to be not unique?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#modules" id="id65">Modules</a><ul>
<li><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id66">How do I create a .pyc file?</a></li>
<li><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id67">How do I find the current module name?</a></li>
<li><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id68">How can I have modules that mutually import each other?</a></li>
<li><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id69">__import__(『x.y.z』) returns <module 『x』>; how do I get z?</a></li>
<li><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id70">When I edit an imported module and reimport it, the changes don’t show up. Why does this happen?</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-questions">
<h2><a class="toc-backref" href="#id3">常見問題</a><a class="headerlink" href="#general-questions" title="本標題的永久連結">¶</a></h2>
<div class="section" id="is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc">
<h3><a class="toc-backref" href="#id4">是否有可以使用在程式碼階段,具有中斷點,步驟執行等功能的除錯器?</a><a class="headerlink" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" title="本標題的永久連結">¶</a></h3>
<p>有的</p>
<p>The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">documented</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">Library</span>
<span class="pre">Reference</span> <span class="pre">Manual</span></code></a>. You can also write your own debugger by using the code
for pdb as an example.</p>
<p>The IDLE interactive development environment, which is part of the standard
Python distribution (normally available as Tools/scripts/idle), includes a
graphical debugger.</p>
<p>PythonWin is a Python IDE that includes a GUI debugger based on pdb. The
Pythonwin debugger colors breakpoints and has quite a few cool features such as
debugging non-Pythonwin programs. Pythonwin is available as part of the <a class="reference external" href="https://sourceforge.net/projects/pywin32/">Python
for Windows Extensions</a> project and
as a part of the ActivePython distribution (see
<a class="reference external" href="https://www.activestate.com/activepython">https://www.activestate.com/activepython</a>).</p>
<p><a class="reference external" href="http://boa-constructor.sourceforge.net/">Boa Constructor</a> is an IDE and GUI
builder that uses wxWidgets. It offers visual frame creation and manipulation,
an object inspector, many views on the source like object browsers, inheritance
hierarchies, doc string generated html documentation, an advanced debugger,
integrated help, and Zope support.</p>
<p><a class="reference external" href="http://eric-ide.python-projects.org/">Eric</a> is an IDE built on PyQt
and the Scintilla editing component.</p>
<p>Pydb is a version of the standard Python debugger pdb, modified for use with DDD
(Data Display Debugger), a popular graphical debugger front end. Pydb can be
found at <a class="reference external" href="http://bashdb.sourceforge.net/pydb/">http://bashdb.sourceforge.net/pydb/</a> and DDD can be found at
<a class="reference external" href="https://www.gnu.org/software/ddd">https://www.gnu.org/software/ddd</a>.</p>
<p>有數個商業化Python整合化開發工具包含圖形除錯功能。這些包含:</p>
<ul class="simple">
<li>Wing IDE (<a class="reference external" href="https://wingware.com/">https://wingware.com/</a>)</li>
<li>Komodo IDE (<a class="reference external" href="https://komodoide.com/">https://komodoide.com/</a>)</li>
<li>PyCharm (<a class="reference external" href="https://www.jetbrains.com/pycharm/">https://www.jetbrains.com/pycharm/</a>)</li>
</ul>
</div>
<div class="section" id="is-there-a-tool-to-help-find-bugs-or-perform-static-analysis">
<h3><a class="toc-backref" href="#id5">有沒有工具幫忙找 bug或執行靜態分析</a><a class="headerlink" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" title="本標題的永久連結">¶</a></h3>
<p>有的</p>
<p>PyChecker is a static analysis tool that finds bugs in Python source code and
warns about code complexity and style. You can get PyChecker from
<a class="reference external" href="http://pychecker.sourceforge.net/">http://pychecker.sourceforge.net/</a>.</p>
<p><a class="reference external" href="https://www.pylint.org/">Pylint</a> is another tool that checks
if a module satisfies a coding standard, and also makes it possible to write
plug-ins to add a custom feature. In addition to the bug checking that
PyChecker performs, Pylint offers some additional features such as checking line
length, whether variable names are well-formed according to your coding
standard, whether declared interfaces are fully implemented, and more.
<a class="reference external" href="https://docs.pylint.org/">https://docs.pylint.org/</a> provides a full list of Pylint’s features.</p>
</div>
<div class="section" id="how-can-i-create-a-stand-alone-binary-from-a-python-script">
<h3><a class="toc-backref" href="#id6">How can I create a stand-alone binary from a Python script?</a><a class="headerlink" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" title="本標題的永久連結">¶</a></h3>
<p>You don’t need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first. There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.</p>
<p>One is to use the freeze tool, which is included in the Python source tree as
<code class="docutils literal notranslate"><span class="pre">Tools/freeze</span></code>. It converts Python byte code to C arrays; a C compiler you can
embed all your modules into a new program, which is then linked with the
standard Python modules.</p>
<p>It works by scanning your source recursively for import statements (in both
forms) and looking for the modules in the standard Python path as well as in the
source directory (for built-in modules). It then turns the bytecode for modules
written in Python into C code (array initializers that can be turned into code
objects using the marshal module) and creates a custom-made config file that
only contains those built-in modules which are actually used in the program. It
then compiles the generated C code and links it with the rest of the Python
interpreter to form a self-contained binary which acts exactly like your script.</p>
<p>Obviously, freeze requires a C compiler. There are several other utilities
which don’t. One is Thomas Heller’s py2exe (Windows only) at</p>
<blockquote>
<div><a class="reference external" href="http://www.py2exe.org/">http://www.py2exe.org/</a></div></blockquote>
<p>Another tool is Anthony Tuininga’s <a class="reference external" href="https://anthony-tuininga.github.io/cx_Freeze/">cx_Freeze</a>.</p>
</div>
<div class="section" id="are-there-coding-standards-or-a-style-guide-for-python-programs">
<h3><a class="toc-backref" href="#id7">Are there coding standards or a style guide for Python programs?</a><a class="headerlink" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" title="本標題的永久連結">¶</a></h3>
<p>Yes. The coding style required for standard library modules is documented as
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a>.</p>
</div>
</div>
<div class="section" id="core-language">
<h2><a class="toc-backref" href="#id8">Core Language</a><a class="headerlink" href="#core-language" title="本標題的永久連結">¶</a></h2>
<div class="section" id="why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value">
<h3><a class="toc-backref" href="#id9">為什麼當變數有值時我得到錯誤訊息 UnboundLocalError</a><a class="headerlink" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" title="本標題的永久連結">¶</a></h3>
<p>It can be a surprise to get the UnboundLocalError in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.</p>
<p>這段程式碼:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">bar</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">bar</span><span class="p">()</span>
<span class="go">10</span>
</pre></div>
</div>
<p>可以執行,但是這段程式:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>導致UnboundLocalError</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">foo</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">UnboundLocalError</span>: <span class="n">local variable 'x' referenced before assignment</span>
</pre></div>
</div>
<p>This is because when you make an assignment to a variable in a scope, that
variable becomes local to that scope and shadows any similarly named variable
in the outer scope. Since the last statement in foo assigns a new value to
<code class="docutils literal notranslate"><span class="pre">x</span></code>, the compiler recognizes it as a local variable. Consequently when the
earlier <code class="docutils literal notranslate"><span class="pre">print(x)</span></code> attempts to print the uninitialized local variable and
an error results.</p>
<p>In the example above you can access the outer scope variable by declaring it
global:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">>>> </span><span class="k">def</span> <span class="nf">foobar</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">global</span> <span class="n">x</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">>>> </span><span class="n">foobar</span><span class="p">()</span>
<span class="go">10</span>
</pre></div>
</div>
<p>This explicit declaration is required in order to remind you that (unlike the
superficially analogous situation with class and instance variables) you are
actually modifying the value of the variable in the outer scope:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">11</span>
</pre></div>
</div>
<p>You can do a similar thing in a nested scope using the <a class="reference internal" href="../reference/simple_stmts.html#nonlocal"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">nonlocal</span></code></a>
keyword:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">... </span> <span class="k">def</span> <span class="nf">bar</span><span class="p">():</span>
<span class="gp">... </span> <span class="k">nonlocal</span> <span class="n">x</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">... </span> <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">... </span> <span class="n">bar</span><span class="p">()</span>
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">foo</span><span class="p">()</span>
<span class="go">10</span>
<span class="go">11</span>
</pre></div>
</div>
</div>
<div class="section" id="what-are-the-rules-for-local-and-global-variables-in-python">
<h3><a class="toc-backref" href="#id10">Python 的區域變數和全域變數有什麼規則?</a><a class="headerlink" href="#what-are-the-rules-for-local-and-global-variables-in-python" title="本標題的永久連結">¶</a></h3>
<p>In Python, variables that are only referenced inside a function are implicitly
global. If a variable is assigned a value anywhere within the function’s body,
it’s assumed to be a local unless explicitly declared as global.</p>
<p>Though a bit surprising at first, a moment’s consideration explains this. On
one hand, requiring <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> for assigned variables provides a bar
against unintended side-effects. On the other hand, if <code class="docutils literal notranslate"><span class="pre">global</span></code> was required
for all global references, you’d be using <code class="docutils literal notranslate"><span class="pre">global</span></code> all the time. You’d have
to declare as global every reference to a built-in function or to a component of
an imported module. This clutter would defeat the usefulness of the <code class="docutils literal notranslate"><span class="pre">global</span></code>
declaration for identifying side-effects.</p>
</div>
<div class="section" id="why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result">
<h3><a class="toc-backref" href="#id11">Why do lambdas defined in a loop with different values all return the same result?</a><a class="headerlink" href="#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" title="本標題的永久連結">¶</a></h3>
<p>Assume you use a for loop to define a few different lambdas (or even plain
functions), e.g.:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>This gives you a list that contains 5 lambdas that calculate <code class="docutils literal notranslate"><span class="pre">x**2</span></code>. You
might expect that, when called, they would return, respectively, <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">1</span></code>,
<code class="docutils literal notranslate"><span class="pre">4</span></code>, <code class="docutils literal notranslate"><span class="pre">9</span></code>, and <code class="docutils literal notranslate"><span class="pre">16</span></code>. However, when you actually try you will see that
they all return <code class="docutils literal notranslate"><span class="pre">16</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
<span class="go">16</span>
<span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="mi">4</span><span class="p">]()</span>
<span class="go">16</span>
</pre></div>
</div>
<p>This happens because <code class="docutils literal notranslate"><span class="pre">x</span></code> is not local to the lambdas, but is defined in
the outer scope, and it is accessed when the lambda is called — not when it
is defined. At the end of the loop, the value of <code class="docutils literal notranslate"><span class="pre">x</span></code> is <code class="docutils literal notranslate"><span class="pre">4</span></code>, so all the
functions now return <code class="docutils literal notranslate"><span class="pre">4**2</span></code>, i.e. <code class="docutils literal notranslate"><span class="pre">16</span></code>. You can also verify this by
changing the value of <code class="docutils literal notranslate"><span class="pre">x</span></code> and see how the results of the lambdas change:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">8</span>
<span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
<span class="go">64</span>
</pre></div>
</div>
<p>In order to avoid this, you need to save the values in variables local to the
lambdas, so that they don’t rely on the value of the global <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">>>> </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="gp">... </span> <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="k">lambda</span> <span class="n">n</span><span class="o">=</span><span class="n">x</span><span class="p">:</span> <span class="n">n</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>Here, <code class="docutils literal notranslate"><span class="pre">n=x</span></code> creates a new variable <code class="docutils literal notranslate"><span class="pre">n</span></code> local to the lambda and computed
when the lambda is defined so that it has the same value that <code class="docutils literal notranslate"><span class="pre">x</span></code> had at
that point in the loop. This means that the value of <code class="docutils literal notranslate"><span class="pre">n</span></code> will be <code class="docutils literal notranslate"><span class="pre">0</span></code>
in the first lambda, <code class="docutils literal notranslate"><span class="pre">1</span></code> in the second, <code class="docutils literal notranslate"><span class="pre">2</span></code> in the third, and so on.
Therefore each lambda will now return the correct result:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
<span class="go">4</span>
<span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="mi">4</span><span class="p">]()</span>
<span class="go">16</span>
</pre></div>
</div>
<p>Note that this behaviour is not peculiar to lambdas, but applies to regular
functions too.</p>
</div>
<div class="section" id="how-do-i-share-global-variables-across-modules">
<h3><a class="toc-backref" href="#id12">How do I share global variables across modules?</a><a class="headerlink" href="#how-do-i-share-global-variables-across-modules" title="本標題的永久連結">¶</a></h3>
<p>The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg). Just import the config
module in all modules of your application; the module then becomes available as
a global name. Because there is only one instance of each module, any changes
made to the module object get reflected everywhere. For example:</p>
<p>config.py:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1"># Default value of the 'x' configuration setting</span>
</pre></div>
</div>
<p>mod.py:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">config</span>
<span class="n">config</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>main.py:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">config</span>
<span class="kn">import</span> <span class="nn">mod</span>
<span class="nb">print</span><span class="p">(</span><span class="n">config</span><span class="o">.</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that using a module is also the basis for implementing the Singleton design
pattern, for the same reason.</p>
</div>
<div class="section" id="what-are-the-best-practices-for-using-import-in-a-module">
<h3><a class="toc-backref" href="#id13">What are the 「best practices」 for using import in a module?</a><a class="headerlink" href="#what-are-the-best-practices-for-using-import-in-a-module" title="本標題的永久連結">¶</a></h3>
<p>In general, don’t use <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">modulename</span> <span class="pre">import</span> <span class="pre">*</span></code>. Doing so clutters the
importer’s namespace, and makes it much harder for linters to detect undefined
names.</p>
<p>Import modules at the top of a file. Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.</p>
<p>It’s good practice if you import modules in the following order:</p>
<ol class="arabic simple">
<li>standard library modules – e.g. <code class="docutils literal notranslate"><span class="pre">sys</span></code>, <code class="docutils literal notranslate"><span class="pre">os</span></code>, <code class="docutils literal notranslate"><span class="pre">getopt</span></code>, <code class="docutils literal notranslate"><span class="pre">re</span></code></li>
<li>third-party library modules (anything installed in Python’s site-packages
directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc.</li>
<li>locally-developed modules</li>
</ol>
<p>It is sometimes necessary to move imports to a function or class to avoid
problems with circular imports. Gordon McMillan says:</p>
<blockquote>
<div>Circular imports are fine where both modules use the 「import <module>」 form
of import. They fail when the 2nd module wants to grab a name out of the
first (「from module import name」) and the import is at the top level. That’s
because names in the 1st are not yet available, because the first module is
busy importing the 2nd.</div></blockquote>
<p>In this case, if the second module is only used in one function, then the import
can easily be moved into that function. By the time the import is called, the
first module will have finished initializing, and the second module can do its
import.</p>
<p>It may also be necessary to move imports out of the top level of code if some of
the modules are platform-specific. In that case, it may not even be possible to
import all of the modules at the top of the file. In this case, importing the
correct modules in the corresponding platform-specific code is a good option.</p>
<p>Only move imports into a local scope, such as inside a function definition, if
it’s necessary to solve a problem such as avoiding a circular import or are
trying to reduce the initialization time of a module. This technique is
especially helpful if many of the imports are unnecessary depending on how the
program executes. You may also want to move imports into a function if the
modules are only ever used in that function. Note that loading a module the
first time may be expensive because of the one time initialization of the
module, but loading a module multiple times is virtually free, costing only a
couple of dictionary lookups. Even if the module name has gone out of scope,
the module is probably available in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>.</p>
</div>
<div class="section" id="why-are-default-values-shared-between-objects">
<h3><a class="toc-backref" href="#id14">Why are default values shared between objects?</a><a class="headerlink" href="#why-are-default-values-shared-between-objects" title="本標題的永久連結">¶</a></h3>
<p>This type of bug commonly bites neophyte programmers. Consider this function:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">mydict</span><span class="o">=</span><span class="p">{}):</span> <span class="c1"># Danger: shared reference to one dict for all calls</span>
<span class="o">...</span> <span class="n">compute</span> <span class="n">something</span> <span class="o">...</span>
<span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
<span class="k">return</span> <span class="n">mydict</span>
</pre></div>
</div>
<p>The first time you call this function, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> contains a single item. The
second time, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> contains two items because when <code class="docutils literal notranslate"><span class="pre">foo()</span></code> begins
executing, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> starts out with an item already in it.</p>
<p>It is often expected that a function call creates new objects for default
values. This is not what happens. Default values are created exactly once, when
the function is defined. If that object is changed, like the dictionary in this
example, subsequent calls to the function will refer to this changed object.</p>
<p>By definition, immutable objects such as numbers, strings, tuples, and <code class="docutils literal notranslate"><span class="pre">None</span></code>,
are safe from change. Changes to mutable objects such as dictionaries, lists,
and class instances can lead to confusion.</p>
<p>Because of this feature, it is good programming practice to not use mutable
objects as default values. Instead, use <code class="docutils literal notranslate"><span class="pre">None</span></code> as the default value and
inside the function, check if the parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code> and create a new
list/dictionary/whatever if it is. For example, don’t write:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">mydict</span><span class="o">=</span><span class="p">{}):</span>
<span class="o">...</span>
</pre></div>
</div>
<p>but:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">mydict</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="k">if</span> <span class="n">mydict</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="n">mydict</span> <span class="o">=</span> <span class="p">{}</span> <span class="c1"># create a new dict for local namespace</span>
</pre></div>
</div>
<p>This feature can be useful. When you have a function that’s time-consuming to
compute, a common technique is to cache the parameters and the resulting value
of each call to the function, and return the cached value if the same value is
requested again. This is called 「memoizing」, and can be implemented like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Callers can only provide two parameters and optionally pass _cache by keyword</span>
<span class="k">def</span> <span class="nf">expensive</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="o">*</span><span class="p">,</span> <span class="n">_cache</span><span class="o">=</span><span class="p">{}):</span>
<span class="k">if</span> <span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span> <span class="ow">in</span> <span class="n">_cache</span><span class="p">:</span>
<span class="k">return</span> <span class="n">_cache</span><span class="p">[(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)]</span>
<span class="c1"># Calculate the value</span>
<span class="n">result</span> <span class="o">=</span> <span class="o">...</span> <span class="n">expensive</span> <span class="n">computation</span> <span class="o">...</span>
<span class="n">_cache</span><span class="p">[(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)]</span> <span class="o">=</span> <span class="n">result</span> <span class="c1"># Store result in the cache</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>You could use a global variable containing a dictionary instead of the default
value; it’s a matter of taste.</p>
</div>
<div class="section" id="how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another">
<h3><a class="toc-backref" href="#id15">How can I pass optional or keyword parameters from one function to another?</a><a class="headerlink" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" title="本標題的永久連結">¶</a></h3>
<p>Collect the arguments using the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> specifiers in the function’s
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary. You can then pass these arguments when
calling another function by using <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="o">...</span>
<span class="n">kwargs</span><span class="p">[</span><span class="s1">'width'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'14.3c'</span>
<span class="o">...</span>
<span class="n">g</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="what-is-the-difference-between-arguments-and-parameters">
<span id="faq-argument-vs-parameter"></span><span id="index-1"></span><h3><a class="toc-backref" href="#id16">What is the difference between arguments and parameters?</a><a class="headerlink" href="#what-is-the-difference-between-arguments-and-parameters" title="本標題的永久連結">¶</a></h3>
<p><a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">Parameters</span></a> are defined by the names that appear in a
function definition, whereas <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a> are the values
actually passed to a function when calling it. Parameters define what types of
arguments a function can accept. For example, given the function definition:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="k">pass</span>
</pre></div>
</div>
<p><em>foo</em>, <em>bar</em> and <em>kwargs</em> are parameters of <code class="docutils literal notranslate"><span class="pre">func</span></code>. However, when calling
<code class="docutils literal notranslate"><span class="pre">func</span></code>, for example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">func</span><span class="p">(</span><span class="mi">42</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="mi">314</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">somevar</span><span class="p">)</span>
</pre></div>
</div>
<p>the values <code class="docutils literal notranslate"><span class="pre">42</span></code>, <code class="docutils literal notranslate"><span class="pre">314</span></code>, and <code class="docutils literal notranslate"><span class="pre">somevar</span></code> are arguments.</p>
</div>
<div class="section" id="why-did-changing-list-y-also-change-list-x">
<h3><a class="toc-backref" href="#id17">Why did changing list 『y』 also change list 『x』?</a><a class="headerlink" href="#why-did-changing-list-y-also-change-list-x" title="本標題的永久連結">¶</a></h3>
<p>If you wrote code like:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">>>> </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span>
<span class="gp">>>> </span><span class="n">y</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">y</span>
<span class="go">[10]</span>
<span class="gp">>>> </span><span class="n">x</span>
<span class="go">[10]</span>
</pre></div>
</div>
<p>you might be wondering why appending an element to <code class="docutils literal notranslate"><span class="pre">y</span></code> changed <code class="docutils literal notranslate"><span class="pre">x</span></code> too.</p>
<p>There are two factors that produce this result:</p>
<ol class="arabic simple">
<li>Variables are simply names that refer to objects. Doing <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">x</span></code> doesn’t
create a copy of the list – it creates a new variable <code class="docutils literal notranslate"><span class="pre">y</span></code> that refers to
the same object <code class="docutils literal notranslate"><span class="pre">x</span></code> refers to. This means that there is only one object
(the list), and both <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> refer to it.</li>
<li>Lists are <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>, which means that you can change their content.</li>
</ol>
<p>After the call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>, the content of the mutable object has
changed from <code class="docutils literal notranslate"><span class="pre">[]</span></code> to <code class="docutils literal notranslate"><span class="pre">[10]</span></code>. Since both the variables refer to the same
object, using either name accesses the modified value <code class="docutils literal notranslate"><span class="pre">[10]</span></code>.</p>
<p>If we instead assign an immutable object to <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">5</span> <span class="c1"># ints are immutable</span>
<span class="gp">>>> </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span>
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># 5 can't be mutated, we are creating a new object here</span>
<span class="gp">>>> </span><span class="n">x</span>
<span class="go">6</span>
<span class="gp">>>> </span><span class="n">y</span>
<span class="go">5</span>
</pre></div>
</div>
<p>we can see that in this case <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> are not equal anymore. This is
because integers are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, and when we do <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span> <span class="pre">1</span></code> we are not
mutating the int <code class="docutils literal notranslate"><span class="pre">5</span></code> by incrementing its value; instead, we are creating a
new object (the int <code class="docutils literal notranslate"><span class="pre">6</span></code>) and assigning it to <code class="docutils literal notranslate"><span class="pre">x</span></code> (that is, changing which
object <code class="docutils literal notranslate"><span class="pre">x</span></code> refers to). After this assignment we have two objects (the ints
<code class="docutils literal notranslate"><span class="pre">6</span></code> and <code class="docutils literal notranslate"><span class="pre">5</span></code>) and two variables that refer to them (<code class="docutils literal notranslate"><span class="pre">x</span></code> now refers to
<code class="docutils literal notranslate"><span class="pre">6</span></code> but <code class="docutils literal notranslate"><span class="pre">y</span></code> still refers to <code class="docutils literal notranslate"><span class="pre">5</span></code>).</p>
<p>Some operations (for example <code class="docutils literal notranslate"><span class="pre">y.append(10)</span></code> and <code class="docutils literal notranslate"><span class="pre">y.sort()</span></code>) mutate the
object, whereas superficially similar operations (for example <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">[10]</span></code>
and <code class="docutils literal notranslate"><span class="pre">sorted(y)</span></code>) create a new object. In general in Python (and in all cases
in the standard library) a method that mutates an object will return <code class="docutils literal notranslate"><span class="pre">None</span></code>
to help avoid getting the two types of operations confused. So if you
mistakenly write <code class="docutils literal notranslate"><span class="pre">y.sort()</span></code> thinking it will give you a sorted copy of <code class="docutils literal notranslate"><span class="pre">y</span></code>,
you’ll instead end up with <code class="docutils literal notranslate"><span class="pre">None</span></code>, which will likely cause your program to
generate an easily diagnosed error.</p>
<p>However, there is one class of operations where the same operation sometimes
has different behaviors with different types: the augmented assignment
operators. For example, <code class="docutils literal notranslate"><span class="pre">+=</span></code> mutates lists but not tuples or ints (<code class="docutils literal notranslate"><span class="pre">a_list</span>
<span class="pre">+=</span> <span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a_list.extend([1,</span> <span class="pre">2,</span> <span class="pre">3])</span></code> and mutates
<code class="docutils literal notranslate"><span class="pre">a_list</span></code>, whereas <code class="docutils literal notranslate"><span class="pre">some_tuple</span> <span class="pre">+=</span> <span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code> and <code class="docutils literal notranslate"><span class="pre">some_int</span> <span class="pre">+=</span> <span class="pre">1</span></code> create
new objects).</p>
<p>In other words:</p>
<ul class="simple">
<li>If we have a mutable object (<a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>,
etc.), we can use some specific operations to mutate it and all the variables
that refer to it will see the change.</li>
<li>If we have an immutable object (<a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>,
etc.), all the variables that refer to it will always see the same value,
but operations that transform that value into a new value always return a new
object.</li>
</ul>
<p>If you want to know if two variables refer to the same object or not, you can
use the <a class="reference internal" href="../reference/expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator, or the built-in function <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a>.</p>
</div>
<div class="section" id="how-do-i-write-a-function-with-output-parameters-call-by-reference">
<h3><a class="toc-backref" href="#id18">How do I write a function with output parameters (call by reference)?</a><a class="headerlink" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" title="本標題的永久連結">¶</a></h3>
<p>Remember that arguments are passed by assignment in Python. Since assignment
just creates references to objects, there’s no alias between an argument name in
the caller and callee, and so no call-by-reference per se. You can achieve the
desired effect in a number of ways.</p>
<ol class="arabic">
<li><p class="first">By returning a tuple of the results:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func2</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="n">a</span> <span class="o">=</span> <span class="s1">'new-value'</span> <span class="c1"># a and b are local names</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">b</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># assigned to new objects</span>
<span class="k">return</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="c1"># return new values</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="s1">'old-value'</span><span class="p">,</span> <span class="mi">99</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">func2</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="c1"># output: new-value 100</span>
</pre></div>
</div>
<p>This is almost always the clearest solution.</p>
</li>
<li><p class="first">By using global variables. This isn’t thread-safe, and is not recommended.</p>
</li>
<li><p class="first">By passing a mutable (changeable in-place) object:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func1</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
<span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'new-value'</span> <span class="c1"># 'a' references a mutable list</span>
<span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># changes a shared object</span>
<span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'old-value'</span><span class="p">,</span> <span class="mi">99</span><span class="p">]</span>
<span class="n">func1</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span> <span class="c1"># output: new-value 100</span>
</pre></div>
</div>
</li>
<li><p class="first">By passing in a dictionary that gets mutated:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func3</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="n">args</span><span class="p">[</span><span class="s1">'a'</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'new-value'</span> <span class="c1"># args is a mutable dictionary</span>
<span class="n">args</span><span class="p">[</span><span class="s1">'b'</span><span class="p">]</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="s1">'b'</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># change it in-place</span>
<span class="n">args</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'a'</span><span class="p">:</span> <span class="s1">'old-value'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">:</span> <span class="mi">99</span><span class="p">}</span>
<span class="n">func3</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">args</span><span class="p">[</span><span class="s1">'a'</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="s1">'b'</span><span class="p">])</span>
</pre></div>
</div>
</li>
<li><p class="first">Or bundle up values in a class instance:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">callByRef</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">args</span><span class="p">):</span>
<span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="ow">in</span> <span class="n">args</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">func4</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="n">args</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s1">'new-value'</span> <span class="c1"># args is a mutable callByRef</span>
<span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">+</span> <span class="mi">1</span> <span class="c1"># change object in-place</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">callByRef</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="s1">'old-value'</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">99</span><span class="p">)</span>
<span class="n">func4</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>There’s almost never a good reason to get this complicated.</p>
</li>
</ol>
<p>Your best choice is to return a tuple containing the multiple results.</p>
</div>
<div class="section" id="how-do-you-make-a-higher-order-function-in-python">
<h3><a class="toc-backref" href="#id19">How do you make a higher order function in Python?</a><a class="headerlink" href="#how-do-you-make-a-higher-order-function-in-python" title="本標題的永久連結">¶</a></h3>
<p>You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define <code class="docutils literal notranslate"><span class="pre">linear(a,b)</span></code> which returns a
function <code class="docutils literal notranslate"><span class="pre">f(x)</span></code> that computes the value <code class="docutils literal notranslate"><span class="pre">a*x+b</span></code>. Using nested scopes:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">linear</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="k">def</span> <span class="nf">result</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="n">b</span>
<span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>Or using a callable object:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">linear</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span>
</pre></div>
</div>
<p>In both cases,</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">taxes</span> <span class="o">=</span> <span class="n">linear</span><span class="p">(</span><span class="mf">0.3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>gives a callable object where <code class="docutils literal notranslate"><span class="pre">taxes(10e6)</span> <span class="pre">==</span> <span class="pre">0.3</span> <span class="pre">*</span> <span class="pre">10e6</span> <span class="pre">+</span> <span class="pre">2</span></code>.</p>
<p>The callable object approach has the disadvantage that it is a bit slower and
results in slightly longer code. However, note that a collection of callables
can share their signature via inheritance:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">exponential</span><span class="p">(</span><span class="n">linear</span><span class="p">):</span>
<span class="c1"># __init__ inherited</span>
<span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>Object can encapsulate state for several methods:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">counter</span><span class="p">:</span>
<span class="n">value</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">def</span> <span class="nf">set</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">x</span>
<span class="k">def</span> <span class="nf">up</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">+</span> <span class="mi">1</span>
<span class="k">def</span> <span class="nf">down</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">-</span> <span class="mi">1</span>
<span class="n">count</span> <span class="o">=</span> <span class="n">counter</span><span class="p">()</span>
<span class="n">inc</span><span class="p">,</span> <span class="n">dec</span><span class="p">,</span> <span class="n">reset</span> <span class="o">=</span> <span class="n">count</span><span class="o">.</span><span class="n">up</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">down</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">set</span>
</pre></div>
</div>
<p>Here <code class="docutils literal notranslate"><span class="pre">inc()</span></code>, <code class="docutils literal notranslate"><span class="pre">dec()</span></code> and <code class="docutils literal notranslate"><span class="pre">reset()</span></code> act like functions which share the
same counting variable.</p>
</div>
<div class="section" id="how-do-i-copy-an-object-in-python">
<h3><a class="toc-backref" href="#id20">How do I copy an object in Python?</a><a class="headerlink" href="#how-do-i-copy-an-object-in-python" title="本標題的永久連結">¶</a></h3>
<p>In general, try <a class="reference internal" href="../library/copy.html#copy.copy" title="copy.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.copy()</span></code></a> or <a class="reference internal" href="../library/copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a> for the general case.
Not all objects can be copied, but most can.</p>
<p>Some objects can be copied more easily. Dictionaries have a <a class="reference internal" href="../library/stdtypes.html#dict.copy" title="dict.copy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>
method:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">newdict</span> <span class="o">=</span> <span class="n">olddict</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
</pre></div>
</div>
<p>Sequences can be copied by slicing:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">new_l</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:]</span>
</pre></div>
</div>
</div>
<div class="section" id="how-can-i-find-the-methods-or-attributes-of-an-object">
<h3><a class="toc-backref" href="#id21">How can I find the methods or attributes of an object?</a><a class="headerlink" href="#how-can-i-find-the-methods-or-attributes-of-an-object" title="本標題的永久連結">¶</a></h3>
<p>For an instance x of a user-defined class, <code class="docutils literal notranslate"><span class="pre">dir(x)</span></code> returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.</p>
</div>
<div class="section" id="how-can-my-code-discover-the-name-of-an-object">
<h3><a class="toc-backref" href="#id22">How can my code discover the name of an object?</a><a class="headerlink" href="#how-can-my-code-discover-the-name-of-an-object" title="本標題的永久連結">¶</a></h3>
<p>Generally speaking, it can’t, because objects don’t really have names.
Essentially, assignment always binds a name to a value; The same is true of
<code class="docutils literal notranslate"><span class="pre">def</span></code> and <code class="docutils literal notranslate"><span class="pre">class</span></code> statements, but in that case the value is a
callable. Consider the following code:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="gp">... </span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">>>> </span><span class="n">B</span> <span class="o">=</span> <span class="n">A</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">B</span><span class="p">()</span>
<span class="gp">>>> </span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="go"><__main__.A object at 0x16D07CC></span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go"><__main__.A object at 0x16D07CC></span>
</pre></div>
</div>
<p>Arguably the class has a name: even though it is bound to two names and invoked
through the name B the created instance is still reported as an instance of
class A. However, it is impossible to say whether the instance’s name is a or
b, since both names are bound to the same value.</p>
<p>Generally speaking it should not be necessary for your code to 「know the names」
of particular values. Unless you are deliberately writing introspective
programs, this is usually an indication that a change of approach might be
beneficial.</p>
<p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
this question:</p>
<blockquote>
<div><p>The same way as you get the name of that cat you found on your porch: the cat
(object) itself cannot tell you its name, and it doesn’t really care – so
the only way to find out what it’s called is to ask all your neighbours
(namespaces) if it’s their cat (object)…</p>
<p>….and don’t be surprised if you’ll find that it’s known by many names, or
no name at all!</p>
</div></blockquote>
</div>
<div class="section" id="what-s-up-with-the-comma-operator-s-precedence">
<h3><a class="toc-backref" href="#id23">What’s up with the comma operator’s precedence?</a><a class="headerlink" href="#what-s-up-with-the-comma-operator-s-precedence" title="本標題的永久連結">¶</a></h3>
<p>Comma is not an operator in Python. Consider this session:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s2">"a"</span> <span class="ow">in</span> <span class="s2">"b"</span><span class="p">,</span> <span class="s2">"a"</span>
<span class="go">(False, 'a')</span>
</pre></div>
</div>
<p>Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="s2">"a"</span> <span class="ow">in</span> <span class="s2">"b"</span><span class="p">),</span> <span class="s2">"a"</span>
</pre></div>
</div>
<p>not:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="s2">"a"</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">"b"</span><span class="p">,</span> <span class="s2">"a"</span><span class="p">)</span>
</pre></div>
</div>
<p>The same is true of the various assignment operators (<code class="docutils literal notranslate"><span class="pre">=</span></code>, <code class="docutils literal notranslate"><span class="pre">+=</span></code> etc). They
are not truly operators but syntactic delimiters in assignment statements.</p>
</div>
<div class="section" id="is-there-an-equivalent-of-c-s-ternary-operator">
<h3><a class="toc-backref" href="#id24">Is there an equivalent of C’s 「?:」 ternary operator?</a><a class="headerlink" href="#is-there-an-equivalent-of-c-s-ternary-operator" title="本標題的永久連結">¶</a></h3>
<p>Yes, there is. The syntax is as follows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">on_true</span><span class="p">]</span> <span class="k">if</span> <span class="p">[</span><span class="n">expression</span><span class="p">]</span> <span class="k">else</span> <span class="p">[</span><span class="n">on_false</span><span class="p">]</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">25</span>
<span class="n">small</span> <span class="o">=</span> <span class="n">x</span> <span class="k">if</span> <span class="n">x</span> <span class="o"><</span> <span class="n">y</span> <span class="k">else</span> <span class="n">y</span>
</pre></div>
</div>
<p>Before this syntax was introduced in Python 2.5, a common idiom was to use
logical operators:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">expression</span><span class="p">]</span> <span class="ow">and</span> <span class="p">[</span><span class="n">on_true</span><span class="p">]</span> <span class="ow">or</span> <span class="p">[</span><span class="n">on_false</span><span class="p">]</span>
</pre></div>
</div>
<p>However, this idiom is unsafe, as it can give wrong results when <em>on_true</em>
has a false boolean value. Therefore, it is always better to use
the <code class="docutils literal notranslate"><span class="pre">...</span> <span class="pre">if</span> <span class="pre">...</span> <span class="pre">else</span> <span class="pre">...</span></code> form.</p>
</div>
<div class="section" id="is-it-possible-to-write-obfuscated-one-liners-in-python">
<h3><a class="toc-backref" href="#id25">Is it possible to write obfuscated one-liners in Python?</a><a class="headerlink" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" title="本標題的永久連結">¶</a></h3>
<p>Yes. Usually this is done by nesting <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> within
<a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a>. See the following three examples, due to Ulf Bartelt:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">functools</span> <span class="k">import</span> <span class="n">reduce</span>
<span class="c1"># Primes < 1000</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">filter</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">*</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">!=</span><span class="mi">0</span><span class="p">,</span>
<span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">%</span><span class="n">x</span><span class="p">,</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="nb">int</span><span class="p">(</span><span class="nb">pow</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="mf">0.5</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">))),</span><span class="mi">1</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1000</span><span class="p">)))))</span>
<span class="c1"># First 10 Fibonacci numbers</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">)</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="n">f</span><span class="p">))</span> <span class="k">if</span> <span class="n">x</span><span class="o">></span><span class="mi">1</span> <span class="k">else</span> <span class="mi">1</span><span class="p">:</span>
<span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">),</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))))</span>
<span class="c1"># Mandelbrot set</span>
<span class="nb">print</span><span class="p">((</span><span class="k">lambda</span> <span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="p">,</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="p">,</span><span class="n">IM</span><span class="p">,</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="p">:</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">,</span>
<span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">,</span><span class="n">L</span><span class="o">=</span><span class="k">lambda</span> <span class="n">yc</span><span class="p">,</span><span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">i</span><span class="o">=</span><span class="n">IM</span><span class="p">,</span>
<span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">:</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">xc</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">yc</span><span class="o">=</span><span class="n">yc</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span>
<span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="p">,</span><span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">F</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">k</span><span class="o"><=</span><span class="mi">0</span><span class="p">)</span><span class="ow">or</span> <span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="n">y</span>
<span class="o">>=</span><span class="mf">4.0</span><span class="p">)</span> <span class="ow">or</span> <span class="mi">1</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">-</span><span class="n">y</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">xc</span><span class="p">,</span><span class="mf">2.0</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">yc</span><span class="p">,</span><span class="n">k</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="nb">chr</span><span class="p">(</span>
<span class="mi">64</span><span class="o">+</span><span class="n">F</span><span class="p">(</span><span class="n">Ru</span><span class="o">+</span><span class="n">x</span><span class="o">*</span><span class="p">(</span><span class="n">Ro</span><span class="o">-</span><span class="n">Ru</span><span class="p">)</span><span class="o">/</span><span class="n">Sx</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="n">i</span><span class="p">)),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sx</span><span class="p">))):</span><span class="n">L</span><span class="p">(</span><span class="n">Iu</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="p">(</span><span class="n">Io</span><span class="o">-</span><span class="n">Iu</span><span class="p">)</span><span class="o">/</span><span class="n">Sy</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sy</span>
<span class="p">))))(</span><span class="o">-</span><span class="mf">2.1</span><span class="p">,</span> <span class="mf">0.7</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.2</span><span class="p">,</span> <span class="mf">1.2</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="mi">24</span><span class="p">))</span>
<span class="c1"># \___ ___/ \___ ___/ | | |__ lines on screen</span>
<span class="c1"># V V | |______ columns on screen</span>
<span class="c1"># | | |__________ maximum of "iterations"</span>
<span class="c1"># | |_________________ range on y axis</span>
<span class="c1"># |____________________________ range on x axis</span>
</pre></div>
</div>
<p>Don’t try this at home, kids!</p>
</div>
</div>
<div class="section" id="numbers-and-strings">
<h2><a class="toc-backref" href="#id26">Numbers and strings</a><a class="headerlink" href="#numbers-and-strings" title="本標題的永久連結">¶</a></h2>
<div class="section" id="how-do-i-specify-hexadecimal-and-octal-integers">
<h3><a class="toc-backref" href="#id27">How do I specify hexadecimal and octal integers?</a><a class="headerlink" href="#how-do-i-specify-hexadecimal-and-octal-integers" title="本標題的永久連結">¶</a></h3>
<p>To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase 「o」. For example, to set the variable 「a」 to the octal value 「10」
(8 in decimal), type:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="mo">0o10</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">8</span>
</pre></div>
</div>
<p>Hexadecimal is just as easy. Simply precede the hexadecimal number with a zero,
and then a lower or uppercase 「x」. Hexadecimal digits can be specified in lower
or uppercase. For example, in the Python interpreter:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="mh">0xa5</span>
<span class="gp">>>> </span><span class="n">a</span>
<span class="go">165</span>
<span class="gp">>>> </span><span class="n">b</span> <span class="o">=</span> <span class="mh">0XB2</span>
<span class="gp">>>> </span><span class="n">b</span>
<span class="go">178</span>
</pre></div>
</div>
</div>
<div class="section" id="why-does-22-10-return-3">
<h3><a class="toc-backref" href="#id28">Why does -22 // 10 return -3?</a><a class="headerlink" href="#why-does-22-10-return-3" title="本標題的永久連結">¶</a></h3>
<p>It’s primarily driven by the desire that <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> have the same sign as <code class="docutils literal notranslate"><span class="pre">j</span></code>.
If you want that, and also want:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">==</span> <span class="p">(</span><span class="n">i</span> <span class="o">//</span> <span class="n">j</span><span class="p">)</span> <span class="o">*</span> <span class="n">j</span> <span class="o">+</span> <span class="p">(</span><span class="n">i</span> <span class="o">%</span> <span class="n">j</span><span class="p">)</span>
</pre></div>
</div>
<p>then integer division has to return the floor. C also requires that identity to
hold, and then compilers that truncate <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">//</span> <span class="pre">j</span></code> need to make <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> have
the same sign as <code class="docutils literal notranslate"><span class="pre">i</span></code>.</p>
<p>There are few real use cases for <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> when <code class="docutils literal notranslate"><span class="pre">j</span></code> is negative. When <code class="docutils literal notranslate"><span class="pre">j</span></code>
is positive, there are many, and in virtually all of them it’s more useful for
<code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> to be <code class="docutils literal notranslate"><span class="pre">>=</span> <span class="pre">0</span></code>. If the clock says 10 now, what did it say 200 hours
ago? <code class="docutils literal notranslate"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">2</span></code> is useful; <code class="docutils literal notranslate"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">-10</span></code> is a bug waiting to
bite.</p>
</div>
<div class="section" id="how-do-i-convert-a-string-to-a-number">
<h3><a class="toc-backref" href="#id29">How do I convert a string to a number?</a><a class="headerlink" href="#how-do-i-convert-a-string-to-a-number" title="本標題的永久連結">¶</a></h3>
<p>For integers, use the built-in <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> type constructor, e.g. <code class="docutils literal notranslate"><span class="pre">int('144')</span>
<span class="pre">==</span> <span class="pre">144</span></code>. Similarly, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> converts to floating-point,
e.g. <code class="docutils literal notranslate"><span class="pre">float('144')</span> <span class="pre">==</span> <span class="pre">144.0</span></code>.</p>
<p>By default, these interpret the number as decimal, so that <code class="docutils literal notranslate"><span class="pre">int('0144')</span> <span class="pre">==</span>
<span class="pre">144</span></code> and <code class="docutils literal notranslate"><span class="pre">int('0x144')</span></code> raises <a class="reference internal" href="../library/exceptions.html#ValueError" title="ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>. <code class="docutils literal notranslate"><span class="pre">int(string,</span> <span class="pre">base)</span></code> takes
the base to convert from as a second optional argument, so <code class="docutils literal notranslate"><span class="pre">int('0x144',</span> <span class="pre">16)</span> <span class="pre">==</span>
<span class="pre">324</span></code>. If the base is specified as 0, the number is interpreted using Python’s
rules: a leading 『0o』 indicates octal, and 『0x』 indicates a hex number.</p>
<p>Do not use the built-in function <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> if all you need is to convert
strings to numbers. <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> will be significantly slower and it presents a
security risk: someone could pass you a Python expression that might have
unwanted side effects. For example, someone could pass
<code class="docutils literal notranslate"><span class="pre">__import__('os').system("rm</span> <span class="pre">-rf</span> <span class="pre">$HOME")</span></code> which would erase your home
directory.</p>
<p><a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> also has the effect of interpreting numbers as Python expressions,
so that e.g. <code class="docutils literal notranslate"><span class="pre">eval('09')</span></code> gives a syntax error because Python does not allow
leading 『0』 in a decimal number (except 『0』).</p>
</div>
<div class="section" id="how-do-i-convert-a-number-to-a-string">
<h3><a class="toc-backref" href="#id30">How do I convert a number to a string?</a><a class="headerlink" href="#how-do-i-convert-a-number-to-a-string" title="本標題的永久連結">¶</a></h3>
<p>To convert, e.g., the number 144 to the string 『144』, use the built-in type
constructor <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>. If you want a hexadecimal or octal representation, use
the built-in functions <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a> or <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a>. For fancy formatting, see
the <a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">Formatted string literals</span></a> and <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a> sections,
e.g. <code class="docutils literal notranslate"><span class="pre">"{:04d}".format(144)</span></code> yields
<code class="docutils literal notranslate"><span class="pre">'0144'</span></code> and <code class="docutils literal notranslate"><span class="pre">"{:.3f}".format(1.0/3.0)</span></code> yields <code class="docutils literal notranslate"><span class="pre">'0.333'</span></code>.</p>
</div>
<div class="section" id="how-do-i-modify-a-string-in-place">
<h3><a class="toc-backref" href="#id31">How do I modify a string in place?</a><a class="headerlink" href="#how-do-i-modify-a-string-in-place" title="本標題的永久連結">¶</a></h3>
<p>You can’t, because strings are immutable. In most situations, you should
simply construct a new string from the various parts you want to assemble
it from. However, if you need an object with the ability to modify in-place
unicode data, try using an <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> object or the <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a>
module:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span> <span class="nn">io</span>
<span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s2">"Hello, world"</span>
<span class="gp">>>> </span><span class="n">sio</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">>>> </span><span class="n">sio</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
<span class="go">'Hello, world'</span>
<span class="gp">>>> </span><span class="n">sio</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">7</span>
<span class="gp">>>> </span><span class="n">sio</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"there!"</span><span class="p">)</span>
<span class="go">6</span>
<span class="gp">>>> </span><span class="n">sio</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
<span class="go">'Hello, there!'</span>
<span class="gp">>>> </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">'u'</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">array('u', 'Hello, world')</span>
<span class="gp">>>> </span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'y'</span>
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">array('u', 'yello, world')</span>
<span class="gp">>>> </span><span class="n">a</span><span class="o">.</span><span class="n">tounicode</span><span class="p">()</span>
<span class="go">'yello, world'</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-use-strings-to-call-functions-methods">
<h3><a class="toc-backref" href="#id32">How do I use strings to call functions/methods?</a><a class="headerlink" href="#how-do-i-use-strings-to-call-functions-methods" title="本標題的永久連結">¶</a></h3>
<p>There are various techniques.</p>
<ul>
<li><p class="first">The best is to use a dictionary that maps strings to functions. The primary
advantage of this technique is that the strings do not need to match the names
of the functions. This is also the primary technique used to emulate a case
construct:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">a</span><span class="p">():</span>
<span class="k">pass</span>
<span class="k">def</span> <span class="nf">b</span><span class="p">():</span>
<span class="k">pass</span>
<span class="n">dispatch</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'go'</span><span class="p">:</span> <span class="n">a</span><span class="p">,</span> <span class="s1">'stop'</span><span class="p">:</span> <span class="n">b</span><span class="p">}</span> <span class="c1"># Note lack of parens for funcs</span>
<span class="n">dispatch</span><span class="p">[</span><span class="n">get_input</span><span class="p">()]()</span> <span class="c1"># Note trailing parens to call function</span>
</pre></div>
</div>
</li>
<li><p class="first">Use the built-in function <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">foo</span>
<span class="nb">getattr</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="s1">'bar'</span><span class="p">)()</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> works on any object, including classes, class
instances, modules, and so on.</p>
<p>This is used in several places in the standard library, like this:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
<span class="k">def</span> <span class="nf">do_foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="o">...</span>
<span class="k">def</span> <span class="nf">do_bar</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="o">...</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">foo_instance</span><span class="p">,</span> <span class="s1">'do_'</span> <span class="o">+</span> <span class="n">opname</span><span class="p">)</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
</li>
<li><p class="first">Use <a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> or <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> to resolve the function name:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">myFunc</span><span class="p">():</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"hello"</span><span class="p">)</span>
<span class="n">fname</span> <span class="o">=</span> <span class="s2">"myFunc"</span>