- Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathprogramming.po
4258 lines (3750 loc) · 168 KB
/
programming.po
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
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001-2025, Python Software Foundation
# This file is distributed under the same license as the Python package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
# Translators:
# Rafael Fontenelle <rffontenelle@gmail.com>, 2025
#
#,fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python 3.12\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2025-04-18 14:52+0000\n"
"PO-Revision-Date: 2024-05-11 00:32+0000\n"
"Last-Translator: Rafael Fontenelle <rffontenelle@gmail.com>, 2025\n"
"Language-Team: Chinese (China) (https://app.transifex.com/python-doc/teams/5390/zh_CN/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: zh_CN\n"
"Plural-Forms: nplurals=1; plural=0;\n"
#:../../faq/programming.rst:5
msgid"Programming FAQ"
msgstr"编程常见问题"
#:../../faq/programming.rst:8
msgid"Contents"
msgstr"目录"
#:../../faq/programming.rst:12
msgid"General Questions"
msgstr"一般问题"
#:../../faq/programming.rst:15
msgid""
"Is there a source code level debugger with breakpoints, single-stepping, "
"etc.?"
msgstr"Python 有没有提供带有断点、单步调试等功能的源码级调试器?"
#:../../faq/programming.rst:17../../faq/programming.rst:58
msgid"Yes."
msgstr"有的。"
#:../../faq/programming.rst:19
msgid""
"Several debuggers for Python are described below, and the built-in function "
":func:`breakpoint` allows you to drop into any of them."
msgstr"以下介绍了一些 Python 的调试器,用内置函数 :func:`breakpoint` 即可切入这些调试器中。"
#:../../faq/programming.rst:22
msgid""
"The pdb module is a simple but adequate console-mode debugger for Python. It"
" is part of the standard Python library, and is :mod:`documented in the "
"Library Reference Manual <pdb>`. You can also write your own debugger by "
"using the code for pdb as an example."
msgstr""
"pdb 模块是一个简单但是够用的控制台模式 Python 调试器。 它是标准 Python 库的一部分,并且 :mod:`已收录于库参考手册 "
"<pdb>`。 你也可以通过使用 pdb 代码作为样例来编写你自己的调试器。"
#:../../faq/programming.rst:27
msgid""
"The IDLE interactive development environment, which is part of the standard "
"Python distribution (normally available as `Tools/scripts/idle3 "
"<https://github.com/python/cpython/blob/main/Tools/scripts/idle3>`_), "
"includes a graphical debugger."
msgstr""
"作为标准 Python 发行版组成部分的 IDLE 交互式开发环境 (通常位于 `Tools/scripts/idle3 "
"<https://github.com/python/cpython/blob/main/Tools/scripts/idle3>`_),包括一个图形化的调试器。"
#:../../faq/programming.rst:32
msgid""
"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 "
"`pywin32 <https://github.com/mhammond/pywin32>`_ project and as a part of "
"the `ActivePython <https://www.activestate.com/products/python/>`_ "
"distribution."
msgstr""
"PythonWin 是一种 Python IDE,其中包含了一个基于 pdb 的 GUI 调试器。PythonWin "
"的调试器会为断点着色,并提供了相当多的超酷特性,例如调试非 PythonWin 程序等。PythonWin 是 `pywin32 "
"<https://github.com/mhammond/pywin32>`_ 项目的组成部分,也是 `ActivePython "
"<https://www.activestate.com/products/python/>`_ 发行版的组成部分。"
#:../../faq/programming.rst:39
msgid""
"`Eric <https://eric-ide.python-projects.org/>`_ is an IDE built on PyQt and "
"the Scintilla editing component."
msgstr""
"`Eric <https://eric-ide.python-projects.org/>`_ 是一个基于 PyQt 和 Scintilla 编辑组件的"
" IDE。"
#:../../faq/programming.rst:42
msgid""
"`trepan3k <https://github.com/rocky/python3-trepan/>`_ is a gdb-like "
"debugger."
msgstr""
"`trepan3k <https://github.com/rocky/python3-trepan/>`_ 是一个类似 gdb 的调试器。"
#:../../faq/programming.rst:44
msgid""
"`Visual Studio Code <https://code.visualstudio.com/>`_ is an IDE with "
"debugging tools that integrates with version-control software."
msgstr""
"`Visual Studio Code <https://code.visualstudio.com/>`_ 是包含了调试工具的 "
"IDE,并集成了版本控制软件。"
#:../../faq/programming.rst:47
msgid""
"There are a number of commercial Python IDEs that include graphical "
"debuggers. They include:"
msgstr"有许多商业 Python IDE 都包含了图形化调试器。包括:"
#:../../faq/programming.rst:50
msgid"`Wing IDE <https://wingware.com/>`_"
msgstr"`Wing IDE <https://wingware.com/>`_"
#:../../faq/programming.rst:51
msgid"`Komodo IDE <https://www.activestate.com/products/komodo-ide/>`_"
msgstr"`Komodo IDE <https://www.activestate.com/products/komodo-ide/>`_"
#:../../faq/programming.rst:52
msgid"`PyCharm <https://www.jetbrains.com/pycharm/>`_"
msgstr"`PyCharm <https://www.jetbrains.com/pycharm/>`_"
#:../../faq/programming.rst:56
msgid"Are there tools to help find bugs or perform static analysis?"
msgstr"是否有能帮助寻找漏洞或执行静态分析的工具?"
#:../../faq/programming.rst:60
msgid""
"`Pylint <https://pylint.pycqa.org/en/latest/index.html>`_ and `Pyflakes "
"<https://github.com/PyCQA/pyflakes>`_ do basic checking that will help you "
"catch bugs sooner."
msgstr""
"`Pylint <https://pylint.pycqa.org/en/latest/index.html>`_ 和 `Pyflakes "
"<https://github.com/PyCQA/pyflakes>`_ 可执行基本检查来帮助你尽早捕捉漏洞。"
#:../../faq/programming.rst:64
msgid""
"Static type checkers such as `Mypy <https://mypy-lang.org/>`_, `Pyre "
"<https://pyre-check.org/>`_, and `Pytype "
"<https://github.com/google/pytype>`_ can check type hints in Python source "
"code."
msgstr""
"静态类型检查器例如 `Mypy <https://mypy-lang.org/>`_, `Pyre <https://pyre-"
"check.org/>`_ 和 `Pytype <https://github.com/google/pytype>`_ 可以检查 Python "
"源代码中的类型提示。"
#:../../faq/programming.rst:73
msgid"How can I create a stand-alone binary from a Python script?"
msgstr"如何由 Python 脚本创建能独立运行的二进制程序?"
#:../../faq/programming.rst:75
msgid""
"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."
msgstr""
"如果只是想要一个独立的程序,以便用户不必预先安装 Python 即可下载和运行它,则不需要将 Python 编译成 C "
"代码。有许多工具可以检测程序所需的模块,并将这些模块与 Python 二进制程序捆绑在一起生成单个可执行文件。"
#:../../faq/programming.rst:81
msgid""
"One is to use the freeze tool, which is included in the Python source tree "
"as `Tools/freeze "
"<https://github.com/python/cpython/tree/main/Tools/freeze>`_. It converts "
"Python byte code to C arrays; with a C compiler you can embed all your "
"modules into a new program, which is then linked with the standard Python "
"modules."
msgstr""
"一种方案是使用 freeze 工具,它以 `Tools/freeze "
"<https://github.com/python/cpython/tree/main/Tools/freeze>`_ 的形式包含在 Python "
"源代码树中。 它可将 Python 字节码转换为 C 数组;你可以使用 C 编译器将你的所有模块嵌入到一个新程序中,再将其与标准 Python "
"模块进行链接。"
#:../../faq/programming.rst:87
msgid""
"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."
msgstr""
"它的工作原理是递归扫描源代码,获取两种格式的 import 语句,并在标准 Python 路径和源码目录(用于内置模块)检索这些模块。然后,把这些模块的"
" Python 字节码转换为 C 代码(可以利用 marshal "
"模块转换为代码对象的数组初始化器),并创建一个定制的配置文件,该文件仅包含程序实际用到的内置模块。然后,编译生成的 C 代码并将其与 Python "
"解释器的其余部分链接,形成一个自给自足的二进制文件,其功能与 Python 脚本代码完全相同。"
#:../../faq/programming.rst:96
msgid""
"The following packages can help with the creation of console and GUI "
"executables:"
msgstr"下列包可以用于帮助创建控制台和 GUI 的可执行文件:"
#:../../faq/programming.rst:99
msgid"`Nuitka <https://nuitka.net/>`_ (Cross-platform)"
msgstr"`Nuitka <https://nuitka.net/>`_ (跨平台)"
#:../../faq/programming.rst:100
msgid"`PyInstaller <https://pyinstaller.org/>`_ (Cross-platform)"
msgstr"`PyInstaller <https://pyinstaller.org/>`_ (跨平台)"
#:../../faq/programming.rst:101
msgid""
"`PyOxidizer <https://pyoxidizer.readthedocs.io/en/stable/>`_ (Cross-"
"platform)"
msgstr"`PyOxidizer <https://pyoxidizer.readthedocs.io/en/stable/>`_ (跨平台)"
#:../../faq/programming.rst:102
msgid""
"`cx_Freeze <https://marcelotduarte.github.io/cx_Freeze/>`_ (Cross-platform)"
msgstr"`cx_Freeze <https://marcelotduarte.github.io/cx_Freeze/>`_ (跨平台)"
#:../../faq/programming.rst:103
msgid"`py2app <https://github.com/ronaldoussoren/py2app>`_ (macOS only)"
msgstr"`py2app <https://github.com/ronaldoussoren/py2app>`_ (仅限 macOS)"
#:../../faq/programming.rst:104
msgid"`py2exe <https://www.py2exe.org/>`_ (Windows only)"
msgstr"`py2exe <https://www.py2exe.org/>`_ (仅限 Windows)"
#:../../faq/programming.rst:107
msgid"Are there coding standards or a style guide for Python programs?"
msgstr"是否有 Python 编码标准或风格指南?"
#:../../faq/programming.rst:109
msgid""
"Yes. The coding style required for standard library modules is documented "
"as :pep:`8`."
msgstr"有的。 标准库模块所要求的编码风格记录于 :pep:`8` 之中。"
#:../../faq/programming.rst:114
msgid"Core Language"
msgstr"语言核心内容"
#:../../faq/programming.rst:119
msgid"Why am I getting an UnboundLocalError when the variable has a value?"
msgstr"变量明明有值,为什么还会出现 UnboundLocalError?"
#:../../faq/programming.rst:121
msgid""
"It can be a surprise to get the :exc:`UnboundLocalError` in previously "
"working code when it is modified by adding an assignment statement somewhere"
" in the body of a function."
msgstr""
"当在函数内部某处添加了一条赋值语句,因而导致之前正常工作的代码报出 :exc:`UnboundLocalError` 错误,这确实有点令人惊讶。"
#:../../faq/programming.rst:125
msgid"This code:"
msgstr"以下代码:"
#:../../faq/programming.rst:134
msgid"works, but this code:"
msgstr"正常工作,但是以下代码"
#:../../faq/programming.rst:141
msgid"results in an :exc:`!UnboundLocalError`:"
msgstr"在 :exc:`!UnboundLocalError` 中的结果:"
#:../../faq/programming.rst:148
msgid""
"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 ``x``, the compiler recognizes it as a local variable. "
"Consequently when the earlier ``print(x)`` attempts to print the "
"uninitialized local variable and an error results."
msgstr""
"原因就是,当对某作用域内的变量进行赋值时,该变量将成为该作用域内的局部变量,并覆盖外部作用域中的同名变量。由于 foo 的最后一条语句为 ``x`` "
"分配了一个新值,编译器会将其识别为局部变量。因此,前面的 ``print(x)`` 试图输出未初始化的局部变量,就会引发错误。"
#:../../faq/programming.rst:155
msgid""
"In the example above you can access the outer scope variable by declaring it"
" global:"
msgstr"在上面的示例中,可以将外部作用域的变量声明为全局变量以便访问:"
#:../../faq/programming.rst:167
msgid""
"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:"
msgstr"与类和实例变量貌似但不一样,其实以上是在修改外部作用域的变量值,为了提示这一点,这里需要显式声明一下。"
#:../../faq/programming.rst:174
msgid""
"You can do a similar thing in a nested scope using the :keyword:`nonlocal` "
"keyword:"
msgstr"你可以使用 :keyword:`nonlocal` 关键字在嵌套作用域中执行类似的操作:"
#:../../faq/programming.rst:192
msgid"What are the rules for local and global variables in Python?"
msgstr"Python 的局部变量和全局变量有哪些规则?"
#:../../faq/programming.rst:194
msgid""
"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."
msgstr""
"函数内部只作引用的 Python 变量隐式视为全局变量。如果在函数内部任何位置为变量赋值,则除非明确声明为全局变量,否则均将其视为局部变量。"
#:../../faq/programming.rst:198
msgid""
"Though a bit surprising at first, a moment's consideration explains this. "
"On one hand, requiring :keyword:`global` for assigned variables provides a "
"bar against unintended side-effects. On the other hand, if ``global`` was "
"required for all global references, you'd be using ``global`` 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 ``global`` declaration for identifying side-effects."
msgstr""
"起初尽管有点令人惊讶,不过考虑片刻即可释然。一方面,已分配的变量要求加上 :keyword:`global` "
"可以防止意外的副作用发生。另一方面,如果所有全局引用都要加上 ``global`` ,那处处都得用上 ``global`` "
"了。那么每次对内置函数或导入模块中的组件进行引用时,都得声明为全局变量。这种杂乱会破坏 ``global`` 声明用于警示副作用的有效性。"
#:../../faq/programming.rst:208
msgid""
"Why do lambdas defined in a loop with different values all return the same "
"result?"
msgstr"为什么在循环中定义的参数各异的 lambda 都返回相同的结果?"
#:../../faq/programming.rst:210
msgid""
"Assume you use a for loop to define a few different lambdas (or even plain "
"functions), e.g.::"
msgstr"假设用 for 循环来定义几个取值各异的 lambda(即便是普通函数也一样):"
#:../../faq/programming.rst:213
msgid""
">>> squares = []\n"
">>> for x in range(5):\n"
"... squares.append(lambda: x**2)"
msgstr""
">>> squares = []\n"
">>> for x in range(5):\n"
"... squares.append(lambda: x**2)"
#:../../faq/programming.rst:217
msgid""
"This gives you a list that contains 5 lambdas that calculate ``x**2``. You "
"might expect that, when called, they would return, respectively, ``0``, "
"``1``, ``4``, ``9``, and ``16``. However, when you actually try you will "
"see that they all return ``16``::"
msgstr""
"以上会得到一个包含5个 lambda 函数的列表,这些函数将计算 ``x**2``。大家或许期望,调用这些函数会分别返回 ``0`` 、``1`` 、 "
"``4`` 、 ``9`` 和 ``16``。然而,真的试过就会发现,他们都会返回 ``16`` :"
#:../../faq/programming.rst:222
msgid""
">>> squares[2]()\n"
"16\n"
">>> squares[4]()\n"
"16"
msgstr""
">>> squares[2]()\n"
"16\n"
">>> squares[4]()\n"
"16"
#:../../faq/programming.rst:227
msgid""
"This happens because ``x`` 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 ``x`` is ``4``, so all "
"the functions now return ``4**2``, i.e. ``16``. You can also verify this by"
" changing the value of ``x`` and see how the results of the lambdas change::"
msgstr""
"这是因为 ``x`` 不是 lambda 函数的内部变量,而是定义于外部作用域中的,并且 ``x`` 是在调用 lambda "
"时访问的——而不是在定义时访问。循环结束时 ``x`` 的值是 ``4`` ,所以此时所有的函数都将返回 ``4**2`` ,即 ``16`` "
"。通过改变 ``x`` 的值并查看 lambda 的结果变化,也可以验证这一点。"
#:../../faq/programming.rst:233
msgid""
">>> x = 8\n"
">>> squares[2]()\n"
"64"
msgstr""
">>> x = 8\n"
">>> squares[2]()\n"
"64"
#:../../faq/programming.rst:237
msgid""
"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 ``x``::"
msgstr"为了避免发生上述情况,需要将值保存在 lambda 局部变量,以使其不依赖于全局 ``x`` 的值:"
#:../../faq/programming.rst:240
msgid""
">>> squares = []\n"
">>> for x in range(5):\n"
"... squares.append(lambda n=x: n**2)"
msgstr""
">>> squares = []\n"
">>> for x in range(5):\n"
"... squares.append(lambda n=x: n**2)"
#:../../faq/programming.rst:244
msgid""
"Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed "
"when the lambda is defined so that it has the same value that ``x`` had at "
"that point in the loop. This means that the value of ``n`` will be ``0`` in"
" the first lambda, ``1`` in the second, ``2`` in the third, and so on. "
"Therefore each lambda will now return the correct result::"
msgstr""
"以上 ``n=x`` 创建了一个新的 lambda 本地变量 ``n``,并在定义 lambda 时计算其值,使其与循环当前时点的 ``x`` "
"值相同。这意味着 ``n`` 的值在第 1 个 lambda 中为 ``0`` ,在第 2 个 lambda 中为 ``1`` ,在第 3 个中为 "
"``2``,依此类推。因此现在每个 lambda 都会返回正确结果:"
#:../../faq/programming.rst:250
msgid""
">>> squares[2]()\n"
"4\n"
">>> squares[4]()\n"
"16"
msgstr""
">>> squares[2]()\n"
"4\n"
">>> squares[4]()\n"
"16"
#:../../faq/programming.rst:255
msgid""
"Note that this behaviour is not peculiar to lambdas, but applies to regular "
"functions too."
msgstr"请注意,上述表现并不是 lambda 所特有的,常规的函数也同样适用。"
#:../../faq/programming.rst:260
msgid"How do I share global variables across modules?"
msgstr"如何跨模块共享全局变量?"
#:../../faq/programming.rst:262
msgid""
"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:"
msgstr""
"在单个程序中跨模块共享信息的规范方法是创建一个特殊模块(通常称为 config 或 cfg)。只需在应用程序的所有模块中导入该 config "
"模块;然后该模块就可当作全局名称使用了。因为每个模块只有一个实例,所以对该模块对象所做的任何更改将会在所有地方得以体现。 例如:"
#:../../faq/programming.rst:268
msgid"config.py::"
msgstr"config.py:"
#:../../faq/programming.rst:270
msgid"x = 0 # Default value of the 'x' configuration setting"
msgstr"x = 0 # 'x' 配置设置的默认值"
#:../../faq/programming.rst:272
msgid"mod.py::"
msgstr"mod.py:"
#:../../faq/programming.rst:274
msgid""
"import config\n"
"config.x = 1"
msgstr""
"import config\n"
"config.x = 1"
#:../../faq/programming.rst:277
msgid"main.py::"
msgstr"main.py:"
#:../../faq/programming.rst:279
msgid""
"import config\n"
"import mod\n"
"print(config.x)"
msgstr""
"import config\n"
"import mod\n"
"print(config.x)"
#:../../faq/programming.rst:283
msgid""
"Note that using a module is also the basis for implementing the singleton "
"design pattern, for the same reason."
msgstr"请注意,出于同样的原因,使用模块也是实现单例设计模式的基础。"
#:../../faq/programming.rst:288
msgid"What are the \"best practices\" for using import in a module?"
msgstr"导入模块的“最佳实践”是什么?"
#:../../faq/programming.rst:290
msgid""
"In general, don't use ``from modulename import *``. Doing so clutters the "
"importer's namespace, and makes it much harder for linters to detect "
"undefined names."
msgstr""
"通常请勿使用 ``from modulename import *`` 。因为这会扰乱 importer 的命名空间,且会造成未定义名称更难以被 "
"Linter 检查出来。"
#:../../faq/programming.rst:294
msgid""
"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."
msgstr""
"请在代码文件的首部就导入模块。这样代码所需的模块就一目了然了,也不用考虑模块名是否在作用域内的问题。每行导入一个模块则增删起来会比较容易,每行导入多个模块则更节省屏幕空间。"
#:../../faq/programming.rst:299
msgid"It's good practice if you import modules in the following order:"
msgstr"按如下顺序导入模块就是一种好做法:"
#:../../faq/programming.rst:301
msgid""
"standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, "
":mod:`re`"
msgstr"标准库模块——例如::mod:`sys`、:mod:`os`、:mod:`argparse`、:mod:`re` 等。"
#:../../faq/programming.rst:302
msgid""
"third-party library modules (anything installed in Python's site-packages "
"directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image`"
msgstr""
"第三方库模块(安装于 Python site-packages "
"目录中的内容)——例如::mod:`!dateutil`、:mod:`!requests`、:mod:`!PIL.Image` 等。"
#:../../faq/programming.rst:304
msgid"locally developed modules"
msgstr"本地开发的模块"
#:../../faq/programming.rst:306
msgid""
"It is sometimes necessary to move imports to a function or class to avoid "
"problems with circular imports. Gordon McMillan says:"
msgstr"为了避免循环导入引发的问题,有时需要将模块导入语句移入函数或类的内部。Gordon McMillan 的说法如下:"
#:../../faq/programming.rst:309
msgid""
"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."
msgstr""
"当两个模块都采用 \"import <module>\" 的导入形式时,循环导入是没有问题的。但如果第 2 个模块想从第 1 "
"个模块中取出一个名称(\"from module import name\")并且导入处于代码的最顶层,那导入就会失败。原因是第 1 "
"个模块中的名称还不可用,这时第 1 个模块正忙于导入第 2 个模块呢。"
#:../../faq/programming.rst:315
msgid""
"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."
msgstr""
"如果只是在一个函数中用到第 2 个模块,那这时将导入语句移入该函数内部即可。当调用到导入语句时,第 1 个模块将已经完成初始化,第 2 "
"个模块就可以进行导入了。"
#:../../faq/programming.rst:320
msgid""
"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."
msgstr""
"如果某些模块是平台相关的,可能还需要把导入语句移出最顶级代码。这种情况下,甚至有可能无法导入文件首部的所有模块。于是在对应的平台相关代码中导入正确的模块,就是一种不错的选择。"
#:../../faq/programming.rst:325
msgid""
"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 :data:`sys.modules`."
msgstr""
"只有为了避免循环导入问题,或有必要减少模块初始化时间时,才把导入语句移入类似函数定义内部的局部作用域。如果根据程序的执行方式,许多导入操作不是必需的,那么这种技术尤其有用。如果模块仅在某个函数中用到,可能还要将导入操作移入该函数内部。请注意,因为模块有一次初始化过程,所以第一次加载模块的代价可能会比较高,但多次加载几乎没有什么花费,代价只是进行几次字典检索而已。即使模块名超出了作用域,模块在"
" :data:`sys.modules` 中也是可用的。 "
#:../../faq/programming.rst:338
msgid"Why are default values shared between objects?"
msgstr"为什么对象之间会共享默认值?"
#:../../faq/programming.rst:340
msgid""
"This type of bug commonly bites neophyte programmers. Consider this "
"function::"
msgstr"新手程序员常常中招这类 Bug。请看以下函数:"
#:../../faq/programming.rst:342
msgid""
"def foo(mydict={}): # Danger: shared reference to one dict for all calls\n"
" ... compute something ...\n"
" mydict[key] = value\n"
" return mydict"
msgstr""
"def foo(mydict={}): # 危险:所有调用共享对一个字典的引用\n"
" ... 执行一些计算 ...\n"
" mydict[key] = value\n"
" return mydict"
#:../../faq/programming.rst:347
msgid""
"The first time you call this function, ``mydict`` contains a single item. "
"The second time, ``mydict`` contains two items because when ``foo()`` begins"
" executing, ``mydict`` starts out with an item already in it."
msgstr""
"第一次调用此函数时, ``mydict`` 中只有一个数据项。第二次调用 ``mydict`` 则会包含两个数据项,因为 ``foo()`` "
"开始执行时, ``mydict`` 中已经带有一个数据项了。"
#:../../faq/programming.rst:351
msgid""
"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."
msgstr""
"大家往往希望,函数调用会为默认值创建新的对象。但事实并非如此。默认值只会在函数定义时创建一次。如果对象发生改变,就如上例中的字典那样,则后续调用该函数时将会引用这个改动的对象。"
#:../../faq/programming.rst:356
msgid""
"By definition, immutable objects such as numbers, strings, tuples, and "
"``None``, are safe from change. Changes to mutable objects such as "
"dictionaries, lists, and class instances can lead to confusion."
msgstr""
"按照定义,不可变对象改动起来是安全的,诸如数字、字符串、元组和 ``None`` 之类。而可变对象的改动则可能引起困惑,例如字典、列表和类实例等。"
#:../../faq/programming.rst:360
msgid""
"Because of this feature, it is good programming practice to not use mutable "
"objects as default values. Instead, use ``None`` as the default value and "
"inside the function, check if the parameter is ``None`` and create a new "
"list/dictionary/whatever if it is. For example, don't write::"
msgstr""
"因此,不把可变对象用作默认值是一种良好的编程做法。而应采用 ``None`` 作为默认值,然后在函数中检查参数是否为 ``None`` "
"并新建列表、字典或其他对象。例如,代码不应如下所示:"
#:../../faq/programming.rst:365
msgid""
"def foo(mydict={}):\n"
" ..."
msgstr""
"def foo(mydict={}):\n"
" ..."
#:../../faq/programming.rst:368
msgid"but::"
msgstr"而应这么写:"
#:../../faq/programming.rst:370
msgid""
"def foo(mydict=None):\n"
" if mydict is None:\n"
" mydict = {} # create a new dict for local namespace"
msgstr""
"def foo(mydict=None):\n"
" if mydict is None:\n"
" mydict = {} # 为局部命名空间新建一个字典"
#:../../faq/programming.rst:374
msgid""
"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::"
msgstr""
"参数默认值的特性有时会很有用处。 "
"如果有个函数的计算过程会比较耗时,有一种常见技巧是将每次函数调用的参数和结果缓存起来,并在同样的值被再次请求时返回缓存的值。这种技巧被称为“memoize”,实现代码可如下所示:"
#:../../faq/programming.rst:379
msgid""
"# Callers can only provide two parameters and optionally pass _cache by keyword\n"
"def expensive(arg1, arg2, *, _cache={}):\n"
" if (arg1, arg2) in _cache:\n"
" return _cache[(arg1, arg2)]\n"
"\n"
" # Calculate the value\n"
" result = ... expensive computation ...\n"
" _cache[(arg1, arg2)] = result # Store result in the cache\n"
" return result"
msgstr""
"# 调用方只能提供两个形参并可选择以关键字形式传入 _cache\n"
"def expensive(arg1, arg2, *, _cache={}):\n"
" if (arg1, arg2) in _cache:\n"
" return _cache[(arg1, arg2)]\n"
"\n"
" # 计算结果值\n"
" result = ... 高耗费的计算 ...\n"
" _cache[(arg1, arg2)] = result # 将结果保存在缓存中\n"
" return result"
#:../../faq/programming.rst:389
msgid""
"You could use a global variable containing a dictionary instead of the "
"default value; it's a matter of taste."
msgstr"也可以不用参数默认值来实现,而是采用全局的字典变量;这取决于个人偏好。"
#:../../faq/programming.rst:394
msgid""
"How can I pass optional or keyword parameters from one function to another?"
msgstr"如何将可选参数或关键字参数从一个函数传递到另一个函数?"
#:../../faq/programming.rst:396
msgid""
"Collect the arguments using the ``*`` and ``**`` 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 ``*`` and ``**``::"
msgstr""
"请利用函数参数列表中的标识符 ``*`` 和 ``**`` 归集实参;结果会是元组形式的位置实参和字典形式的关键字实参。然后就可利用 ``*`` 和 "
"``**`` 在调用其他函数时传入这些实参:"
#:../../faq/programming.rst:401
msgid""
"def f(x, *args, **kwargs):\n"
" ...\n"
" kwargs['width'] = '14.3c'\n"
" ...\n"
" g(x, *args, **kwargs)"
msgstr""
"def f(x, *args, **kwargs):\n"
" ...\n"
" kwargs['width'] = '14.3c'\n"
" ...\n"
" g(x, *args, **kwargs)"
#:../../faq/programming.rst:415
msgid"What is the difference between arguments and parameters?"
msgstr"形参和实参之间有什么区别?"
#:../../faq/programming.rst:417
msgid""
":term:`Parameters <parameter>` are defined by the names that appear in a "
"function definition, whereas :term:`arguments <argument>` are the values "
"actually passed to a function when calling it. Parameters define what "
":term:`kind of arguments <parameter>` a function can accept. For example, "
"given the function definition::"
msgstr""
":term:`形参 <parameter>` 是由出现在函数定义中的名称来定义的,而 :term:`参数 <argument>` "
"则是在调用函数时实际传入的值。 形参定义了一个函数能接受什么 :term:`参数种类 <parameter>`。 例如,对于以下函数定义::"
#:../../faq/programming.rst:423
msgid""
"def func(foo, bar=None, **kwargs):\n"
" pass"
msgstr""
"def func(foo, bar=None, **kwargs):\n"
" pass"
#:../../faq/programming.rst:426
msgid""
"*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling"
" ``func``, for example::"
msgstr"*foo* 、 *bar* 和 *kwargs* 是 ``func`` 的形参。 不过在调用 ``func`` 时,例如:"
#:../../faq/programming.rst:429
msgid"func(42, bar=314, extra=somevar)"
msgstr"func(42, bar=314, extra=somevar)"
#:../../faq/programming.rst:431
msgid"the values ``42``, ``314``, and ``somevar`` are arguments."
msgstr"``42`` 、 ``314`` 和 ``somevar`` 则是实参。"
#:../../faq/programming.rst:435
msgid"Why did changing list 'y' also change list 'x'?"
msgstr"为什么修改列表 'y' 也会更改列表 'x'?"
#:../../faq/programming.rst:437
msgid"If you wrote code like::"
msgstr"如果代码编写如下:"
#:../../faq/programming.rst:439
msgid""
">>> x = []\n"
">>> y = x\n"
">>> y.append(10)\n"
">>> y\n"
"[10]\n"
">>> x\n"
"[10]"
msgstr""
">>> x = []\n"
">>> y = x\n"
">>> y.append(10)\n"
">>> y\n"
"[10]\n"
">>> x\n"
"[10]"
#:../../faq/programming.rst:447
msgid""
"you might be wondering why appending an element to ``y`` changed ``x`` too."
msgstr"或许大家很想知道,为什么在 y 中添加一个元素时, x 也会改变。"
#:../../faq/programming.rst:449
msgid"There are two factors that produce this result:"
msgstr"产生这种结果有两个因素:"
#:../../faq/programming.rst:451
msgid""
"Variables are simply names that refer to objects. Doing ``y = x`` doesn't "
"create a copy of the list -- it creates a new variable ``y`` that refers to "
"the same object ``x`` refers to. This means that there is only one object "
"(the list), and both ``x`` and ``y`` refer to it."
msgstr""
"变量只是指向对象的一个名称。执行 ``y = x`` 并不会创建列表的副本——而只是创建了一个新变量 ``y``,并指向 ``x`` "
"所指的同一对象。这就意味着只存在一个列表对象,``x`` 和 ``y`` 都是对它的引用。"
#:../../faq/programming.rst:455
msgid""
"Lists are :term:`mutable`, which means that you can change their content."
msgstr"列表属于 :term:`mutable` 对象,这意味着它的内容是可以修改的。"
#:../../faq/programming.rst:457
msgid""
"After the call to :meth:`!append`, the content of the mutable object has "
"changed from ``[]`` to ``[10]``. Since both the variables refer to the same"
" object, using either name accesses the modified value ``[10]``."
msgstr""
"在调用 :meth:`!append` 之后,该可变对象的内容由 ``[]`` 变为 ``[10]``。 "
"由于两个变量引用了同一对象,因此用其中任意一个名称所访问到的都是修改后的值 ``[10]``。"
#:../../faq/programming.rst:461
msgid"If we instead assign an immutable object to ``x``::"
msgstr"如果把赋给 ``x`` 的对象换成一个不可变对象:"
#:../../faq/programming.rst:463
msgid""
">>> x = 5 # ints are immutable\n"
">>> y = x\n"
">>> x = x + 1 # 5 can't be mutated, we are creating a new object here\n"
">>> x\n"
"6\n"
">>> y\n"
"5"
msgstr""
">>> x = 5 # 整数是不可变对象\n"
">>> y = x\n"
">>> x = x + 1 # 5 不能被修改,在此我们会新建一个对象\n"
">>> x\n"
"6\n"
">>> y\n"
"5"
#:../../faq/programming.rst:471
msgid""
"we can see that in this case ``x`` and ``y`` are not equal anymore. This is"
" because integers are :term:`immutable`, and when we do ``x = x + 1`` we are"
" not mutating the int ``5`` by incrementing its value; instead, we are "
"creating a new object (the int ``6``) and assigning it to ``x`` (that is, "
"changing which object ``x`` refers to). After this assignment we have two "
"objects (the ints ``6`` and ``5``) and two variables that refer to them "
"(``x`` now refers to ``6`` but ``y`` still refers to ``5``)."
msgstr""
"可见这时 ``x`` 和 ``y`` 就不再相等了。因为整数是 :term:`immutable` 对象,在执行 ``x = x + 1`` "
"时,并不会修改整数对象 ``5``,给它加上 1;而是创建了一个新的对象(整数对象 ``6`` )并将其赋给 ``x`` (也就是改变了 ``x`` "
"所指向的对象)。在赋值完成后,就有了两个对象(整数对象 ``6`` 和 ``5`` )和分别指向他俩的两个变量( ``x`` 现在指向 ``6`` 而 "
"``y`` 仍然指向 ``5`` )。"
#:../../faq/programming.rst:479
msgid""
"Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the "
"object, whereas superficially similar operations (for example ``y = y + "
"[10]`` and :func:`sorted(y) <sorted>`) create a new object. In general in "
"Python (and in all cases in the standard library) a method that mutates an "
"object will return ``None`` to help avoid getting the two types of "
"operations confused. So if you mistakenly write ``y.sort()`` thinking it "
"will give you a sorted copy of ``y``, you'll instead end up with ``None``, "
"which will likely cause your program to generate an easily diagnosed error."
msgstr""
"某些操作 (例如 ``y.append(10)`` 和 ``y.sort()``) 是改变原对象,而看上去相似的另一些操作 (例如 ``y = y + "
"[10]`` 和 :func:`sorted(y) <sorted>) 则是创建新对象。 通常在 Python 中 (以及在标准库的所有代码中) "
"会改变原对象的方法将返回 ``None`` 以帮助避免混淆这两种不同类型的操作。 因此如果你错误地使用了 ``y.sort()`` "
"并期望它将返回一个经过排序的 ``y`` 的副本,你得到的结果将会是 ``None``,这将导致你的程序产生一个容易诊断的错误。"
#:../../faq/programming.rst:488
msgid""
"However, there is one class of operations where the same operation sometimes"
" has different behaviors with different types: the augmented assignment "
"operators. For example, ``+=`` mutates lists but not tuples or ints "
"(``a_list += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and "
"mutates ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += "
"1`` create new objects)."
msgstr""
"不过还存在一类操作,用不同的类型执行相同的操作有时会发生不同的行为:即增量赋值运算符。例如,``+=`` "
"会修改列表,但不会修改元组或整数(``a_list += [1, 2, 3]`` 与 ``a_list.extend([1, 2, 3])`` "
"同样都会改变 ``a_list``,而 ``some_tuple += (1, 2, 3)`` 和 ``some_int += 1`` "
"则会创建新的对象)。"
#:../../faq/programming.rst:495
msgid"In other words:"
msgstr"换而言之:"
#:../../faq/programming.rst:497
msgid""
"If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`, "
"etc.), we can use some specific operations to mutate it and all the "
"variables that refer to it will see the change."
msgstr""
"对于一个可变对象( :class:`list` 、 :class:`dict` 、 :class:`set` "
"等等),可以利用某些特定的操作进行修改,所有引用它的变量都会反映出改动情况。"
#:../../faq/programming.rst:500
msgid""
"If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`, "
"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."
msgstr""
"对于一个不可变对象( :class:`str` 、 :class:`int` 、 :class:`tuple` "
"等),所有引用它的变量都会给出相同的值,但所有改变其值的操作都将返回一个新的对象。"
#:../../faq/programming.rst:505
msgid""
"If you want to know if two variables refer to the same object or not, you "
"can use the :keyword:`is` operator, or the built-in function :func:`id`."
msgstr"如要知道两个变量是否指向同一个对象,可以利用 :keyword:`is` 运算符或内置函数 :func:`id`。"
#:../../faq/programming.rst:510
msgid"How do I write a function with output parameters (call by reference)?"
msgstr"如何编写带有输出参数的函数(按照引用调用)?"
#:../../faq/programming.rst:512
msgid""
"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."
msgstr""
"请记住,Python "
"中的实参是通过赋值传递的。由于赋值只是创建了对象的引用,所以调用方和被调用方的参数名都不存在别名,本质上也就不存在按引用调用的方式。通过以下几种方式,可以得到所需的效果。"
#:../../faq/programming.rst:517
msgid"By returning a tuple of the results::"
msgstr"返回一个元组:"
#:../../faq/programming.rst:519
msgid""
">>> def func1(a, b):\n"
"... a = 'new-value' # a and b are local names\n"
"... b = b + 1 # assigned to new objects\n"
"... return a, b # return new values\n"
"...\n"
">>> x, y = 'old-value', 99\n"
">>> func1(x, y)\n"
"('new-value', 100)"
msgstr""
">>> def func1(a, b):\n"
"... a = 'new-value' # a 和 b 是局部名称\n"
"... b = b + 1 # 赋值为新的对象\n"
"... return a, b # 返回新的值\n"
"...\n"
">>> x, y = 'old-value', 99\n"
">>> func1(x, y)\n"
"('new-value', 100)"
#:../../faq/programming.rst:528
msgid"This is almost always the clearest solution."
msgstr"这差不多是最明晰的解决方案了。"
#:../../faq/programming.rst:530
msgid""
"By using global variables. This isn't thread-safe, and is not recommended."
msgstr"使用全局变量。这不是线程安全的方案,不推荐使用。"
#:../../faq/programming.rst:532
msgid"By passing a mutable (changeable in-place) object::"
msgstr"传递一个可变(即可原地修改的) 对象:"
#:../../faq/programming.rst:534
msgid""
">>> def func2(a):\n"
"... a[0] = 'new-value' # 'a' references a mutable list\n"
"... a[1] = a[1] + 1 # changes a shared object\n"
"...\n"
">>> args = ['old-value', 99]\n"
">>> func2(args)\n"
">>> args\n"
"['new-value', 100]"
msgstr""
">>> def func2(a):\n"
"... a[0] = 'new-value' # 'a' 引用了一个可变的列表\n"
"... a[1] = a[1] + 1 # 修改一个共享对象\n"
"...\n"
">>> args = ['old-value', 99]\n"
">>> func2(args)\n"