-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatamodel.html
More file actions
2507 lines (2420 loc) · 271 KB
/
datamodel.html
File metadata and controls
2507 lines (2420 loc) · 271 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>3. Data model — 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="4. Execution model" href="executionmodel.html" />
<link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" />
<link rel="shortcut icon" type="image/png" href="../_static/py.png" />
<link rel="canonical" href="https://docs.python.org/3/reference/datamodel.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="executionmodel.html" title="4. Execution model"
accesskey="N">下一頁</a> |</li>
<li class="right" >
<a href="lexical_analysis.html" title="2. Lexical analysis"
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">The Python Language Reference</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="data-model">
<span id="datamodel"></span><h1>3. Data model<a class="headerlink" href="#data-model" title="本標題的永久連結">¶</a></h1>
<div class="section" id="objects-values-and-types">
<span id="objects"></span><h2>3.1. Objects, values and types<a class="headerlink" href="#objects-values-and-types" title="本標題的永久連結">¶</a></h2>
<p id="index-0"><em class="dfn">Objects</em> are Python’s abstraction for data. All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
conformance to Von Neumann’s model of a 「stored program computer,」 code is also
represented by objects.)</p>
<span class="target" id="index-1"></span><p>Every object has an identity, a type and a value. An object’s <em>identity</em> never
changes once it has been created; you may think of it as the object’s address in
memory. The 『<a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>』 operator compares the identity of two objects; the
<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> function returns an integer representing its identity.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> For CPython, <code class="docutils literal notranslate"><span class="pre">id(x)</span></code> is the memory address where <code class="docutils literal notranslate"><span class="pre">x</span></code> is stored.</p>
</div>
<p>An object’s type determines the operations that the object supports (e.g., 「does
it have a length?」) and also defines the possible values for objects of that
type. The <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> function returns an object’s type (which is an object
itself). Like its identity, an object’s <em class="dfn">type</em> is also unchangeable.
<a class="footnote-reference" href="#id8" id="id1">[1]</a></p>
<p>The <em>value</em> of some objects can change. Objects whose value can
change are said to be <em>mutable</em>; objects whose value is unchangeable once they
are created are called <em>immutable</em>. (The value of an immutable container object
that contains a reference to a mutable object can change when the latter’s value
is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed. So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.) An
object’s mutability is determined by its type; for instance, numbers, strings
and tuples are immutable, while dictionaries and lists are mutable.</p>
<p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable
they may be garbage-collected. An implementation is allowed to postpone garbage
collection or omit it altogether — it is a matter of implementation quality
how garbage collection is implemented, as long as no objects are collected that
are still reachable.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed
detection of cyclically linked garbage, which collects most objects as soon
as they become unreachable, but is not guaranteed to collect garbage
containing circular references. See the documentation of the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a>
module for information on controlling the collection of cyclic garbage.
Other implementations act differently and CPython may change.
Do not depend on immediate finalization of objects when they become
unreachable (so you should always close files explicitly).</p>
</div>
<p>Note that the use of the implementation’s tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a 『<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>』 statement may keep
objects alive.</p>
<p>Some objects contain references to 「external」 resources such as open files or
windows. It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method. Programs are strongly recommended to explicitly
close such objects. The 『<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>』 statement
and the 『<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>』 statement provide convenient ways to do this.</p>
<p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>.
Examples of containers are tuples, lists and dictionaries. The references are
part of a container’s value. In most cases, when we talk about the value of a
container, we imply the values, not the identities of the contained objects;
however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied. So, if an immutable container
(like a tuple) contains a reference to a mutable object, its value changes if
that mutable object is changed.</p>
<p>Types affect almost all aspects of object behavior. Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed. E.g.,
after <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></code>, <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code> may or may not refer to the same object
with the value one, depending on the implementation, but after <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span>
<span class="pre">[]</span></code>, <code class="docutils literal notranslate"><span class="pre">c</span></code> and <code class="docutils literal notranslate"><span class="pre">d</span></code> are guaranteed to refer to two different, unique, newly
created empty lists. (Note that <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> assigns the same object to both
<code class="docutils literal notranslate"><span class="pre">c</span></code> and <code class="docutils literal notranslate"><span class="pre">d</span></code>.)</p>
</div>
<div class="section" id="the-standard-type-hierarchy">
<span id="types"></span><h2>3.2. The standard type hierarchy<a class="headerlink" href="#the-standard-type-hierarchy" title="本標題的永久連結">¶</a></h2>
<p id="index-4">Below is a list of the types that are built into Python. Extension modules
(written in C, Java, or other languages, depending on the implementation) can
define additional types. Future versions of Python may add types to the type
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.),
although such additions will often be provided via the standard library instead.</p>
<p id="index-5">Some of the type descriptions below contain a paragraph listing 『special
attributes.』 These are attributes that provide access to the implementation and
are not intended for general use. Their definition may change in the future.</p>
<dl class="docutils">
<dt>None</dt>
<dd><p class="first last" id="index-6">This type has a single value. There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal notranslate"><span class="pre">None</span></code>. It is used to signify the
absence of a value in many situations, e.g., it is returned from functions that
don’t explicitly return anything. Its truth value is false.</p>
</dd>
<dt>NotImplemented</dt>
<dd><p class="first" id="index-7">This type has a single value. There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>. Numeric methods
and rich comparison methods should return this value if they do not implement the
operation for the operands provided. (The interpreter will then try the
reflected operation, or some other fallback, depending on the operator.) Its
truth value is true.</p>
<p class="last">See
<a class="reference internal" href="../library/numbers.html#implementing-the-arithmetic-operations"><span class="std std-ref">Implementing the arithmetic operations</span></a>
for more details.</p>
</dd>
<dt>Ellipsis</dt>
<dd><p class="first last" id="index-8">This type has a single value. There is a single object with this value. This
object is accessed through the literal <code class="docutils literal notranslate"><span class="pre">...</span></code> or the built-in name
<code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>. Its truth value is true.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Number</span></code></a></dt>
<dd><p class="first" id="index-9">These are created by numeric literals and returned as results by arithmetic
operators and arithmetic built-in functions. Numeric objects are immutable;
once created their value never changes. Python numbers are of course strongly
related to mathematical numbers, but subject to the limitations of numerical
representation in computers.</p>
<p>Python distinguishes between integers, floating point numbers, and complex
numbers:</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a></dt>
<dd><p class="first" id="index-10">These represent elements from the mathematical set of integers (positive and
negative).</p>
<p>There are two types of integers:</p>
<p>Integers (<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>)</p>
<blockquote>
<div>These represent numbers in an unlimited range, subject to available (virtual)
memory only. For the purpose of shift and mask operations, a binary
representation is assumed, and negative numbers are represented in a variant of
2’s complement which gives the illusion of an infinite string of sign bits
extending to the left.</div></blockquote>
<dl class="docutils">
<dt>Booleans (<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>)</dt>
<dd><p class="first last" id="index-11">These represent the truth values False and True. The two objects representing
the values <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code> are the only Boolean objects. The Boolean type is a
subtype of the integer type, and Boolean values behave like the values 0 and 1,
respectively, in almost all contexts, the exception being that when converted to
a string, the strings <code class="docutils literal notranslate"><span class="pre">"False"</span></code> or <code class="docutils literal notranslate"><span class="pre">"True"</span></code> are returned, respectively.</p>
</dd>
</dl>
<p class="last" id="index-12">The rules for integer representation are intended to give the most meaningful
interpretation of shift and mask operations involving negative integers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>)</dt>
<dd><p class="first last" id="index-13">These represent machine-level double precision floating point numbers. You are
at the mercy of the underlying machine architecture (and C or Java
implementation) for the accepted range and handling of overflow. Python does not
support single-precision floating point numbers; the savings in processor and
memory usage that are usually the reason for using these are dwarfed by the
overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Complex</span></code></a> (<a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>)</dt>
<dd><p class="first last" id="index-14">These represent complex numbers as a pair of machine-level double precision
floating point numbers. The same caveats apply as for floating point numbers.
The real and imaginary parts of a complex number <code class="docutils literal notranslate"><span class="pre">z</span></code> can be retrieved through
the read-only attributes <code class="docutils literal notranslate"><span class="pre">z.real</span></code> and <code class="docutils literal notranslate"><span class="pre">z.imag</span></code>.</p>
</dd>
</dl>
</dd>
<dt>Sequences</dt>
<dd><p class="first" id="index-15">These represent finite ordered sets indexed by non-negative numbers. The
built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the number of items of a sequence. When
the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1,
…, <em>n</em>-1. Item <em>i</em> of sequence <em>a</em> is selected by <code class="docutils literal notranslate"><span class="pre">a[i]</span></code>.</p>
<p id="index-16">Sequences also support slicing: <code class="docutils literal notranslate"><span class="pre">a[i:j]</span></code> selects all items with index <em>k</em> such
that <em>i</em> <code class="docutils literal notranslate"><span class="pre"><=</span></code> <em>k</em> <code class="docutils literal notranslate"><span class="pre"><</span></code> <em>j</em>. When used as an expression, a slice is a
sequence of the same type. This implies that the index set is renumbered so
that it starts at 0.</p>
<p>Some sequences also support 「extended slicing」 with a third 「step」 parameter:
<code class="docutils literal notranslate"><span class="pre">a[i:j:k]</span></code> selects all items of <em>a</em> with index <em>x</em> where <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code>, <em>n</em>
<code class="docutils literal notranslate"><span class="pre">>=</span></code> <code class="docutils literal notranslate"><span class="pre">0</span></code> and <em>i</em> <code class="docutils literal notranslate"><span class="pre"><=</span></code> <em>x</em> <code class="docutils literal notranslate"><span class="pre"><</span></code> <em>j</em>.</p>
<p>Sequences are distinguished according to their mutability:</p>
<dl class="last docutils">
<dt>Immutable sequences</dt>
<dd><p class="first" id="index-17">An object of an immutable sequence type cannot change once it is created. (If
the object contains references to other objects, these other objects may be
mutable and may be changed; however, the collection of objects directly
referenced by an immutable object cannot change.)</p>
<p>The following types are immutable sequences:</p>
<dl class="last docutils" id="index-18">
<dt>字串 (String)</dt>
<dd><p class="first last" id="index-19">A string is a sequence of values that represent Unicode code points.
All the code points in the range <code class="docutils literal notranslate"><span class="pre">U+0000</span> <span class="pre">-</span> <span class="pre">U+10FFFF</span></code> can be
represented in a string. Python doesn’t have a <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code> type;
instead, every code point in the string is represented as a string
object with length <code class="docutils literal notranslate"><span class="pre">1</span></code>. The built-in function <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>
converts a code point from its string form to an integer in the
range <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code>; <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a> converts an integer in the range
<code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code> to the corresponding length <code class="docutils literal notranslate"><span class="pre">1</span></code> string object.
<a class="reference internal" href="../library/stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.encode()</span></code></a> can be used to convert a <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> to
<a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> using the given text encoding, and
<a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a> can be used to achieve the opposite.</p>
</dd>
<dt>Tuples</dt>
<dd><p class="first last" id="index-20">The items of a tuple are arbitrary Python objects. Tuples of two or
more items are formed by comma-separated lists of expressions. A tuple
of one item (a 『singleton』) can be formed by affixing a comma to an
expression (an expression by itself does not create a tuple, since
parentheses must be usable for grouping of expressions). An empty
tuple can be formed by an empty pair of parentheses.</p>
</dd>
<dt>Bytes</dt>
<dd><p class="first last" id="index-21">A bytes object is an immutable array. The items are 8-bit bytes,
represented by integers in the range 0 <= x < 256. Bytes literals
(like <code class="docutils literal notranslate"><span class="pre">b'abc'</span></code>) and the built-in <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytes()</span></code></a> constructor
can be used to create bytes objects. Also, bytes objects can be
decoded to strings via the <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> method.</p>
</dd>
</dl>
</dd>
<dt>Mutable sequences</dt>
<dd><p class="first" id="index-22">Mutable sequences can be changed after they are created. The subscription and
slicing notations can be used as the target of assignment and <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a>
(delete) statements.</p>
<p>There are currently two intrinsic mutable sequence types:</p>
<dl class="docutils">
<dt>List(串列)</dt>
<dd><p class="first last" id="index-23">The items of a list are arbitrary Python objects. Lists are formed by
placing a comma-separated list of expressions in square brackets. (Note
that there are no special cases needed to form lists of length 0 or 1.)</p>
</dd>
<dt>Byte Arrays</dt>
<dd><p class="first last" id="index-24">A bytearray object is a mutable array. They are created by the built-in
<a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a> constructor. Aside from being mutable
(and hence unhashable), byte arrays otherwise provide the same interface
and functionality as immutable <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects.</p>
</dd>
</dl>
<p class="last" id="index-25">The extension module <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> provides an additional example of a
mutable sequence type, as does the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p>
</dd>
</dl>
</dd>
<dt>Set types</dt>
<dd><p class="first" id="index-26">These represent unordered, finite sets of unique, immutable objects. As such,
they cannot be indexed by any subscript. However, they can be iterated over, and
the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the number of items in a set. Common
uses for sets are fast membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.</p>
<p>For set elements, the same immutability rules apply as for dictionary keys. Note
that numeric types obey the normal rules for numeric comparison: if two numbers
compare equal (e.g., <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>), only one of them can be contained in a
set.</p>
<p>There are currently two intrinsic set types:</p>
<dl class="last docutils">
<dt>Sets</dt>
<dd><p class="first last" id="index-27">These represent a mutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a>
constructor and can be modified afterwards by several methods, such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>.</p>
</dd>
<dt>Frozen sets</dt>
<dd><p class="first last" id="index-28">These represent an immutable set. They are created by the built-in
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal notranslate"><span class="pre">frozenset()</span></code></a> constructor. As a frozenset is immutable and
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, it can be used again as an element of another set, or as
a dictionary key.</p>
</dd>
</dl>
</dd>
<dt>Mappings</dt>
<dd><p class="first" id="index-29">These represent finite sets of objects indexed by arbitrary index sets. The
subscript notation <code class="docutils literal notranslate"><span class="pre">a[k]</span></code> selects the item indexed by <code class="docutils literal notranslate"><span class="pre">k</span></code> from the mapping
<code class="docutils literal notranslate"><span class="pre">a</span></code>; this can be used in expressions and as the target of assignments or
<a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statements. The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the number
of items in a mapping.</p>
<p>There is currently a single intrinsic mapping type:</p>
<dl class="last docutils">
<dt>字典</dt>
<dd><p class="first" id="index-30">These represent finite sets of objects indexed by nearly arbitrary values. The
only types of values not acceptable as keys are values containing lists or
dictionaries or other mutable types that are compared by value rather than by
object identity, the reason being that the efficient implementation of
dictionaries requires a key’s hash value to remain constant. Numeric types used
for keys obey the normal rules for numeric comparison: if two numbers compare
equal (e.g., <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>) then they can be used interchangeably to index
the same dictionary entry.</p>
<p>Dictionaries are mutable; they can be created by the <code class="docutils literal notranslate"><span class="pre">{...}</span></code> notation (see
section <a class="reference internal" href="expressions.html#dict"><span class="std std-ref">Dictionary displays</span></a>).</p>
<p class="last" id="index-31">The extension modules <a class="reference internal" href="../library/dbm.html#module-dbm.ndbm" title="dbm.ndbm: The standard "database" interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.ndbm</span></code></a> and <a class="reference internal" href="../library/dbm.html#module-dbm.gnu" title="dbm.gnu: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.gnu</span></code></a> provide
additional examples of mapping types, as does the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module.</p>
</dd>
</dl>
</dd>
<dt>Callable types</dt>
<dd><p class="first" id="index-32">These are the types to which the function call operation (see section
<a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>) can be applied:</p>
<dl class="last docutils">
<dt>User-defined functions</dt>
<dd><p class="first" id="index-33">A user-defined function object is created by a function definition (see
section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>). It should be called with an argument list
containing the same number of items as the function’s formal parameter
list.</p>
<p>Special attributes:</p>
<table border="1" class="docutils" id="index-34">
<colgroup>
<col width="37%" />
<col width="46%" />
<col width="16%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Meaning</th>
<th class="head"> </th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code></td>
<td>The function’s documentation
string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
unavailable; not inherited by
subclasses</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a></td>
<td>The function’s name</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="../library/stdtypes.html#definition.__qualname__" title="definition.__qualname__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__qualname__</span></code></a></td>
<td><p class="first">The function’s
<a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a></p>
<div class="last versionadded">
<p><span class="versionmodified">3.3 版新加入.</span></p>
</div>
</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code></td>
<td>The name of the module the
function was defined in, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__defaults__</span></code></td>
<td>A tuple containing default
argument values for those
arguments that have defaults,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no arguments
have a default value</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__code__</span></code></td>
<td>The code object representing
the compiled function body.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__globals__</span></code></td>
<td>A reference to the dictionary
that holds the function’s
global variables — the
global namespace of the
module in which the function
was defined.</td>
<td>Read-only</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a></td>
<td>The namespace supporting
arbitrary function
attributes.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__closure__</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">None</span></code> or a tuple of cells
that contain bindings for the
function’s free variables.
See below for information on
the <code class="docutils literal notranslate"><span class="pre">cell_contents</span></code>
attribute.</td>
<td>Read-only</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code></td>
<td>A dict containing annotations
of parameters. The keys of
the dict are the parameter
names, and <code class="docutils literal notranslate"><span class="pre">'return'</span></code> for
the return annotation, if
provided.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__kwdefaults__</span></code></td>
<td>A dict containing defaults
for keyword-only parameters.</td>
<td>Writable</td>
</tr>
</tbody>
</table>
<p>Most of the attributes labelled 「Writable」 check the type of the assigned value.</p>
<p>Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions. Regular attribute
dot-notation is used to get and set such attributes. <em>Note that the current
implementation only supports function attributes on user-defined functions.
Function attributes on built-in functions may be supported in the future.</em></p>
<p>A cell object has the attribute <code class="docutils literal notranslate"><span class="pre">cell_contents</span></code>. This can be used to get
the value of the cell, as well as set the value.</p>
<p class="last">Additional information about a function’s definition can be retrieved from its
code object; see the description of internal types below.</p>
</dd>
<dt>Instance methods</dt>
<dd><p class="first" id="index-35">An instance method object combines a class, a class instance and any
callable object (normally a user-defined function).</p>
<p id="index-36">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is the class instance object,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> is the function object; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the method’s
documentation (same as <code class="docutils literal notranslate"><span class="pre">__func__.__doc__</span></code>); <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the
method name (same as <code class="docutils literal notranslate"><span class="pre">__func__.__name__</span></code>); <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is the
name of the module the method was defined in, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p>
<p>Methods also support accessing (but not setting) the arbitrary function
attributes on the underlying function object.</p>
<p>User-defined method objects may be created when getting an attribute of a
class (perhaps via an instance of that class), if that attribute is a
user-defined function object or a class method object.</p>
<p>When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> attribute is the instance, and the method object is said
to be bound. The new method’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> attribute is the original
function object.</p>
<p>When a user-defined method object is created by retrieving another method
object from a class or instance, the behaviour is the same as for a
function object, except that the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> attribute of the new
instance is not the original method object but its <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code>
attribute.</p>
<p>When an instance method object is created by retrieving a class method
object from a class or instance, its <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> attribute is the
class itself, and its <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> attribute is the function object
underlying the class method.</p>
<p>When an instance method object is called, the underlying function
(<code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code>) is called, inserting the class instance
(<code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code>) in front of the argument list. For instance, when
<code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> is a class which contains a definition for a function
<code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code>, and <code class="docutils literal notranslate"><span class="pre">x</span></code> is an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, calling <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> is
equivalent to calling <code class="docutils literal notranslate"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>.</p>
<p>When an instance method object is derived from a class method object, the
「class instance」 stored in <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> will actually be the class
itself, so that calling either <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> or <code class="docutils literal notranslate"><span class="pre">C.f(1)</span></code> is equivalent to
calling <code class="docutils literal notranslate"><span class="pre">f(C,1)</span></code> where <code class="docutils literal notranslate"><span class="pre">f</span></code> is the underlying function.</p>
<p class="last">Note that the transformation from function object to instance method
object happens each time the attribute is retrieved from the instance. In
some cases, a fruitful optimization is to assign the attribute to a local
variable and call that local variable. Also notice that this
transformation only happens for user-defined functions; other callable
objects (and all non-callable objects) are retrieved without
transformation. It is also important to note that user-defined functions
which are attributes of a class instance are not converted to bound
methods; this <em>only</em> happens when the function is an attribute of the
class.</p>
</dd>
<dt>Generator functions</dt>
<dd><p class="first last" id="index-37">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement (see section
<a class="reference internal" href="simple_stmts.html#yield"><span class="std std-ref">The yield statement</span></a>) is called a <em class="dfn">generator function</em>. Such a function, when
called, always returns an iterator object which can be used to execute the
body of the function: calling the iterator’s <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterator.__next__()</span></code></a>
method will cause the function to execute until it provides a value
using the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement. When the function executes a
<a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>
exception is raised and the iterator will have reached the end of the set of
values to be returned.</p>
</dd>
<dt>Coroutine functions</dt>
<dd><p class="first last" id="index-38">A function or method which is defined using <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> is called
a <em class="dfn">coroutine function</em>. Such a function, when called, returns a
<a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> object. It may contain <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions,
as well as <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> and <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statements. See
also the <a class="reference internal" href="#coroutine-objects"><span class="std std-ref">Coroutine Objects</span></a> section.</p>
</dd>
<dt>Asynchronous generator functions</dt>
<dd><p class="first" id="index-39">A function or method which is defined using <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> and
which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is called a
<em class="dfn">asynchronous generator function</em>. Such a function, when called,
returns an asynchronous iterator object which can be used in an
<a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement to execute the body of the function.</p>
<p class="last">Calling the asynchronous iterator’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">aiterator.__anext__()</span></code> method
will return an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> which when awaited
will execute until it provides a value using the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
expression. When the function executes an empty <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception
is raised and the asynchronous iterator will have reached the end of
the set of values to be yielded.</p>
</dd>
<dt>Built-in functions</dt>
<dd><p class="first last" id="index-40">A built-in function object is a wrapper around a C function. Examples of
built-in functions are <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.sin()</span></code></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the function’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
unavailable; <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the function’s name; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is
set to <code class="docutils literal notranslate"><span class="pre">None</span></code> (but see the next item); <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is the name of
the module the function was defined in or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p>
</dd>
<dt>Built-in methods</dt>
<dd><p class="first last" id="index-41">This is really a different disguise of a built-in function, this time containing
an object passed to the C function as an implicit extra argument. An example of
a built-in method is <code class="docutils literal notranslate"><span class="pre">alist.append()</span></code>, assuming <em>alist</em> is a list object. In
this case, the special read-only attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is set to the object
denoted by <em>alist</em>.</p>
</dd>
<dt>Classes</dt>
<dd>Classes are callable. These objects normally act as factories for new
instances of themselves, but variations are possible for class types that
override <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>. The arguments of the call are passed to
<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to
initialize the new instance.</dd>
<dt>Class Instances</dt>
<dd>Instances of arbitrary classes can be made callable by defining a
<a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method in their class.</dd>
</dl>
</dd>
<dt>Modules</dt>
<dd><p class="first" id="index-42">Modules are a basic organizational unit of Python code, and are created by
the <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">import system</span></a> as invoked either by the
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement (see <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>), or by calling
functions such as <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a> and built-in
<a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>. A module object has a namespace implemented by a
dictionary object (this is the dictionary referenced by the <code class="docutils literal notranslate"><span class="pre">__globals__</span></code>
attribute of functions defined in the module). Attribute references are
translated to lookups in this dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">m.x</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">m.__dict__["x"]</span></code>. A module object does not contain the code object used
to initialize the module (since it isn’t needed once the initialization is
done).</p>
<p>Attribute assignment updates the module’s namespace dictionary, e.g.,
<code class="docutils literal notranslate"><span class="pre">m.x</span> <span class="pre">=</span> <span class="pre">1</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.__dict__["x"]</span> <span class="pre">=</span> <span class="pre">1</span></code>.</p>
<p id="index-43">Predefined (writable) attributes: <a class="reference internal" href="import.html#__name__" title="__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the module’s name;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the module’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
unavailable; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code> (optional) is a dictionary containing
<a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">variable annotations</span></a> collected during module
body execution; <a class="reference internal" href="import.html#__file__" title="__file__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code></a> is the pathname of the file from which the
module was loaded, if it was loaded from a file. The <a class="reference internal" href="import.html#__file__" title="__file__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code></a>
attribute may be missing for certain types of modules, such as C modules
that are statically linked into the interpreter; for extension modules
loaded dynamically from a shared library, it is the pathname of the shared
library file.</p>
<p id="index-44">Special read-only attribute: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the module’s
namespace as a dictionary object.</p>
<div class="impl-detail last compound">
<p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module
dictionary will be cleared when the module falls out of scope even if the
dictionary still has live references. To avoid this, copy the dictionary
or keep the module around while using its dictionary directly.</p>
</div>
</dd>
<dt>Custom classes</dt>
<dd><p class="first">Custom class types are typically created by class definitions (see section
<a class="reference internal" href="compound_stmts.html#class"><span class="std std-ref">Class definitions</span></a>). A class has a namespace implemented by a dictionary object.
Class attribute references are translated to lookups in this dictionary, e.g.,
<code class="docutils literal notranslate"><span class="pre">C.x</span></code> is translated to <code class="docutils literal notranslate"><span class="pre">C.__dict__["x"]</span></code> (although there are a number of
hooks which allow for other means of locating attributes). When the attribute
name is not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order which
behaves correctly even in the presence of 『diamond』 inheritance structures
where there are multiple inheritance paths leading back to a common ancestor.
Additional details on the C3 MRO used by Python can be found in the
documentation accompanying the 2.3 release at
<a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
<p id="index-45">When a class attribute reference (for class <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, say) would yield a
class method object, it is transformed into an instance method object whose
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> attribute is <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>. When it would yield a static
method object, it is transformed into the object wrapped by the static method
object. See section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for another way in which attributes
retrieved from a class may differ from those actually contained in its
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p>
<p id="index-46">Class attribute assignments update the class’s dictionary, never the dictionary
of a base class.</p>
<p id="index-47">A class object can be called (see above) to yield a class instance (see below).</p>
<p class="last" id="index-48">Special attributes: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the class name; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is
the module name in which the class was defined; <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the
dictionary containing the class’s namespace; <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> is a
tuple containing the base classes, in the order of their occurrence in the
base class list; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the class’s documentation string,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code> (optional) is a dictionary
containing <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">variable annotations</span></a> collected during
class body execution.</p>
</dd>
<dt>Class instances</dt>
<dd><p class="first" id="index-49">A class instance is created by calling a class object (see above). A class
instance has a namespace implemented as a dictionary which is the first place
in which attribute references are searched. When an attribute is not found
there, and the instance’s class has an attribute by that name, the search
continues with the class attributes. If a class attribute is found that is a
user-defined function object, it is transformed into an instance method
object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> attribute is the instance. Static method and
class method objects are also transformed; see above under 「Classes」. See
section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for another way in which attributes of a class
retrieved via its instances may differ from the objects actually stored in
the class’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. If no class attribute is found, and the
object’s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method, that is called to satisfy
the lookup.</p>
<p id="index-50">Attribute assignments and deletions update the instance’s dictionary, never a
class’s dictionary. If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> or
<a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delattr__()</span></code></a> method, this is called instead of updating the instance
dictionary directly.</p>
<p id="index-51">Class instances can pretend to be numbers, sequences, or mappings if they have
methods with certain special names. See section <a class="reference internal" href="#specialnames"><span class="std std-ref">Special method names</span></a>.</p>
<p class="last" id="index-52">Special attributes: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the attribute dictionary;
<a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> is the instance’s class.</p>
</dd>
<dt>I/O objects (also known as file objects)</dt>
<dd><p class="first" id="index-53">A <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> represents an open file. Various shortcuts are
available to create file objects: the <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> built-in function, and
also <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, <a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a>, and the
<a class="reference internal" href="../library/socket.html#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> method of socket objects (and perhaps by
other functions or methods provided by extension modules).</p>
<p class="last">The objects <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> are
initialized to file objects corresponding to the interpreter’s standard
input, output and error streams; they are all open in text mode and
therefore follow the interface defined by the <a class="reference internal" href="../library/io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.TextIOBase</span></code></a>
abstract class.</p>
</dd>
<dt>Internal types</dt>
<dd><p class="first" id="index-54">A few types used internally by the interpreter are exposed to the user. Their
definitions may change with future versions of the interpreter, but they are
mentioned here for completeness.</p>
<dl class="docutils" id="index-55">
<dt>Code objects</dt>
<dd><p class="first">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>.
The difference between a code object and a function object is that the function
object contains an explicit reference to the function’s globals (the module in
which it was defined), while a code object contains no context; also the default
argument values are stored in the function object, not in the code object
(because they represent values calculated at run-time). Unlike function
objects, code objects are immutable and contain no references (directly or
indirectly) to mutable objects.</p>
<p id="index-56">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_name</span></code> gives the function name;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_argcount</span></code> is the number of positional arguments (including arguments
with default values); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_nlocals</span></code> is the number of local variables used
by the function (including arguments); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_varnames</span></code> is a tuple containing
the names of the local variables (starting with the argument names);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_cellvars</span></code> is a tuple containing the names of local variables that are
referenced by nested functions; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_freevars</span></code> is a tuple containing the
names of free variables; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_code</span></code> is a string representing the sequence
of bytecode instructions; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code> is a tuple containing the literals
used by the bytecode; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code> is a tuple containing the names used by
the bytecode; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_filename</span></code> is the filename from which the code was
compiled; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_firstlineno</span></code> is the first line number of the function;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_lnotab</span></code> is a string encoding the mapping from bytecode offsets to
line numbers (for details see the source code of the interpreter);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_stacksize</span></code> is the required stack size (including local variables);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> is an integer encoding a number of flags for the interpreter.</p>
<p id="index-57">The following flag bits are defined for <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code>: bit <code class="docutils literal notranslate"><span class="pre">0x04</span></code> is set if
the function uses the <code class="docutils literal notranslate"><span class="pre">*arguments</span></code> syntax to accept an arbitrary number of
positional arguments; bit <code class="docutils literal notranslate"><span class="pre">0x08</span></code> is set if the function uses the
<code class="docutils literal notranslate"><span class="pre">**keywords</span></code> syntax to accept arbitrary keyword arguments; bit <code class="docutils literal notranslate"><span class="pre">0x20</span></code> is set
if the function is a generator.</p>
<p>Future feature declarations (<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code>) also use bits
in <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> to indicate whether a code object was compiled with a
particular feature enabled: bit <code class="docutils literal notranslate"><span class="pre">0x2000</span></code> is set if the function was compiled
with future division enabled; bits <code class="docutils literal notranslate"><span class="pre">0x10</span></code> and <code class="docutils literal notranslate"><span class="pre">0x1000</span></code> were used in earlier
versions of Python.</p>
<p>Other bits in <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> are reserved for internal use.</p>
<p class="last" id="index-58">If a code object represents a function, the first item in <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code> is
the documentation string of the function, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined.</p>
</dd>
</dl>
<dl class="docutils" id="frame-objects">
<dt>Frame objects</dt>
<dd><p class="first" id="index-59">Frame objects represent execution frames. They may occur in traceback objects
(see below), and are also passed to registered trace functions.</p>
<p id="index-60">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_back</span></code> is to the previous stack frame
(towards the caller), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if this is the bottom stack frame;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_code</span></code> is the code object being executed in this frame; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_locals</span></code>
is the dictionary used to look up local variables; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_globals</span></code> is used for
global variables; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_builtins</span></code> is used for built-in (intrinsic) names;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lasti</span></code> gives the precise instruction (this is an index into the
bytecode string of the code object).</p>
<p id="index-61">Special writable attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace</span></code>, if not <code class="docutils literal notranslate"><span class="pre">None</span></code>, is a function
called for various events during code execution (this is used by the debugger).
Normally an event is triggered for each new source line - this can be
disabled by setting <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace_lines</span></code> to <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
<p>Implementations <em>may</em> allow per-opcode events to be requested by setting
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace_opcodes</span></code> to <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>. Note that this may lead to
undefined interpreter behaviour if exceptions raised by the trace
function escape to the function being traced.</p>
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code> is the current line number of the frame — writing to this
from within a trace function jumps to the given line (only for the bottom-most
frame). A debugger can implement a Jump command (aka Set Next Statement)
by writing to f_lineno.</p>
<p>Frame objects support one method:</p>
<dl class="last method">
<dt id="frame.clear">
<code class="descclassname">frame.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frame.clear" title="本定義的永久連結">¶</a></dt>
<dd><p>This method clears all references to local variables held by the
frame. Also, if the frame belonged to a generator, the generator
is finalized. This helps break reference cycles involving frame
objects (for example when catching an exception and storing its
traceback for later use).</p>
<p><a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if the frame is currently executing.</p>
<div class="versionadded">
<p><span class="versionmodified">3.4 版新加入.</span></p>
</div>
</dd></dl>
</dd>
</dl>
<dl class="last docutils" id="traceback-objects">
<dt>Traceback objects</dt>
<dd><p class="first" id="index-62">Traceback objects represent a stack trace of an exception. A traceback object
is implicitly created when an exception occurs, and may also be explicitly
created by calling <a class="reference internal" href="../library/types.html#types.TracebackType" title="types.TracebackType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.TracebackType</span></code></a>.</p>
<p>For implicitly created tracebacks, when the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is
inserted in front of the current traceback. When an exception handler is
entered, the stack trace is made available to the program. (See section
<a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>.) It is accessible as the third item of the
tuple returned by <code class="docutils literal notranslate"><span class="pre">sys.exc_info()</span></code>, and as the <code class="docutils literal notranslate"><span class="pre">__traceback__</span></code> attribute
of the caught exception.</p>
<p>When the program contains no suitable
handler, the stack trace is written (nicely formatted) to the standard error
stream; if the interpreter is interactive, it is also made available to the user
as <code class="docutils literal notranslate"><span class="pre">sys.last_traceback</span></code>.</p>
<p>For explicitly created tracebacks, it is up to the creator of the traceback
to determine how the <code class="docutils literal notranslate"><span class="pre">tb_next</span></code> attributes should be linked to form a
full stack trace.</p>
<p id="index-63">Special read-only attributes:
<code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_frame</span></code> points to the execution frame of the current level;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_lineno</span></code> gives the line number where the exception occurred;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_lasti</span></code> indicates the precise instruction.
The line number and last instruction in the traceback may differ from the
line number of its frame object if the exception occurred in a
<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with no matching except clause or with a
finally clause.</p>
<p id="index-64">Special writable attribute: <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_next</span></code> is the next level in the stack
trace (towards the frame where the exception occurred), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
there is no next level.</p>
<div class="last versionchanged">
<p><span class="versionmodified">3.7 版更變: </span>Traceback objects can now be explicitly instantiated from Python code,
and the <code class="docutils literal notranslate"><span class="pre">tb_next</span></code> attribute of existing instances can be updated.</p>
</div>
</dd>
<dt>Slice objects</dt>
<dd><p class="first" id="index-65">Slice objects are used to represent slices for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
methods. They are also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a> function.</p>
<p id="index-66">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code> is the lower bound;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code> is the upper bound; <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code> is the step
value; each is <code class="docutils literal notranslate"><span class="pre">None</span></code> if omitted. These attributes can have any type.</p>
<p>Slice objects support one method:</p>
<dl class="last method">
<dt id="slice.indices">
<code class="descclassname">slice.</code><code class="descname">indices</code><span class="sig-paren">(</span><em>self</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#slice.indices" title="本定義的永久連結">¶</a></dt>
<dd><p>This method takes a single integer argument <em>length</em> and computes
information about the slice that the slice object would describe if
applied to a sequence of <em>length</em> items. It returns a tuple of three
integers; respectively these are the <em>start</em> and <em>stop</em> indices and the
<em>step</em> or stride length of the slice. Missing or out-of-bounds indices
are handled in a manner consistent with regular slices.</p>
</dd></dl>
</dd>
<dt>Static method objects</dt>
<dd>Static method objects provide a way of defeating the transformation of function
objects to method objects described above. A static method object is a wrapper
around any other object, usually a user-defined method object. When a static
method object is retrieved from a class or a class instance, the object actually
returned is the wrapped object, which is not subject to any further
transformation. Static method objects are not themselves callable, although the
objects they wrap usually are. Static method objects are created by the built-in
<a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> constructor.</dd>
<dt>Class method objects</dt>
<dd>A class method object, like a static method object, is a wrapper around another
object that alters the way in which that object is retrieved from classes and
class instances. The behaviour of class method objects upon such retrieval is
described above, under 「User-defined methods」. Class method objects are created
by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> constructor.</dd>
</dl>
</dd>
</dl>
</div>
<div class="section" id="special-method-names">
<span id="specialnames"></span><h2>3.3. Special method names<a class="headerlink" href="#special-method-names" title="本標題的永久連結">¶</a></h2>
<p id="index-67">A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Python’s approach to <em class="dfn">operator overloading</em>,
allowing classes to define their own behavior with respect to language
operators. For instance, if a class defines a method named <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>,
and <code class="docutils literal notranslate"><span class="pre">x</span></code> is an instance of this class, then <code class="docutils literal notranslate"><span class="pre">x[i]</span></code> is roughly equivalent
to <code class="docutils literal notranslate"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></code>. Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
<a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>).</p>
<p>Setting a special method to <code class="docutils literal notranslate"><span class="pre">None</span></code> indicates that the corresponding
operation is not available. For example, if a class sets
<a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> to <code class="docutils literal notranslate"><span class="pre">None</span></code>, the class is not iterable, so calling
<a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> on its instances will raise a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> (without
falling back to <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>). <a class="footnote-reference" href="#id9" id="id2">[2]</a></p>
<p>When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled. For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense. (One example
of this is the <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> interface in the W3C’s Document
Object Model.)</p>
<div class="section" id="basic-customization">
<span id="customization"></span><h3>3.3.1. Basic customization<a class="headerlink" href="#basic-customization" title="本標題的永久連結">¶</a></h3>
<dl class="method">
<dt id="object.__new__">
<code class="descclassname">object.</code><code class="descname">__new__</code><span class="sig-paren">(</span><em>cls</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__new__" title="本定義的永久連結">¶</a></dt>
<dd><p id="index-68">Called to create a new instance of class <em>cls</em>. <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is a static
method (special-cased so you need not declare it as such) that takes the class
of which an instance was requested as its first argument. The remaining
arguments are those passed to the object constructor expression (the call to the
class). The return value of <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> should be the new object instance
(usually an instance of <em>cls</em>).</p>
<p>Typical implementations create a new instance of the class by invoking the
superclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method using <code class="docutils literal notranslate"><span class="pre">super().__new__(cls[,</span> <span class="pre">...])</span></code>
with appropriate arguments and then modifying the newly-created instance
as necessary before returning it.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> returns an instance of <em>cls</em>, then the new instance’s
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method will be invoked like <code class="docutils literal notranslate"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></code>, where
<em>self</em> is the new instance and the remaining arguments are the same as were
passed to <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> does not return an instance of <em>cls</em>, then the new instance’s
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method will not be invoked.</p>
<p><a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is intended mainly to allow subclasses of immutable types (like
int, str, or tuple) to customize instance creation. It is also commonly
overridden in custom metaclasses in order to customize class creation.</p>
</dd></dl>
<dl class="method">
<dt id="object.__init__">
<code class="descclassname">object.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__init__" title="本定義的永久連結">¶</a></dt>
<dd><p id="index-69">Called after the instance has been created (by <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>), but before
it is returned to the caller. The arguments are those passed to the
class constructor expression. If a base class has an <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>
method, the derived class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, if any, must explicitly
call it to ensure proper initialization of the base class part of the
instance; for example: <code class="docutils literal notranslate"><span class="pre">super().__init__([args...])</span></code>.</p>
<p>Because <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> work together in constructing
objects (<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> to create it, and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to customize it),
no non-<code class="docutils literal notranslate"><span class="pre">None</span></code> value may be returned by <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>; doing so will
cause a <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to be raised at runtime.</p>
</dd></dl>
<dl class="method">
<dt id="object.__del__">
<code class="descclassname">object.</code><code class="descname">__del__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__del__" title="本定義的永久連結">¶</a></dt>
<dd><p id="index-70">Called when the instance is about to be destroyed. This is also called a
finalizer or (improperly) a destructor. If a base class has a
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, the derived class’s <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method,
if any, must explicitly call it to ensure proper deletion of the base
class part of the instance.</p>
<p>It is possible (though not recommended!) for the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method
to postpone destruction of the instance by creating a new reference to
it. This is called object <em>resurrection</em>. It is implementation-dependent
whether <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> is called a second time when a resurrected object
is about to be destroyed; the current <a class="reference internal" href="../glossary.html#term-cpython"><span class="xref std std-term">CPython</span></a> implementation
only calls it once.</p>
<p>It is not guaranteed that <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are called for objects
that still exist when the interpreter exits.</p>
<div class="admonition note">
<p class="first admonition-title">備註</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> doesn’t directly call <code class="docutils literal notranslate"><span class="pre">x.__del__()</span></code> — the former decrements
the reference count for <code class="docutils literal notranslate"><span class="pre">x</span></code> by one, and the latter is only called when
<code class="docutils literal notranslate"><span class="pre">x</span></code>’s reference count reaches zero.</p>
</div>
<div class="impl-detail compound">
<p class="compound-first"><strong>CPython implementation detail:</strong> It is possible for a reference cycle to prevent the reference count
of an object from going to zero. In this case, the cycle will be
later detected and deleted by the <a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">cyclic garbage collector</span></a>. A common cause of reference cycles is when
an exception has been caught in a local variable. The frame’s
locals then reference the exception, which references its own
traceback, which references the locals of all frames caught in the
traceback.</p>
<div class="compound-last admonition seealso">
<p class="first admonition-title">也參考</p>
<p class="last">Documentation for the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module.</p>
</div>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>Due to the precarious circumstances under which <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are
invoked, exceptions that occur during their execution are ignored, and a warning
is printed to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> instead. In particular:</p>
<ul class="last simple">
<li><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> can be invoked when arbitrary code is being executed,
including from any arbitrary thread. If <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> needs to take
a lock or invoke any other blocking resource, it may deadlock as
the resource may already be taken by the code that gets interrupted
to execute <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a>.</li>
<li><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> can be executed during interpreter shutdown. As a
consequence, the global variables it needs to access (including other
modules) may already have been deleted or set to <code class="docutils literal notranslate"><span class="pre">None</span></code>. Python
guarantees that globals whose name begins with a single underscore
are deleted from their module before other globals are deleted; if
no other references to such globals exist, this may help in assuring
that imported modules are still available at the time when the
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method is called.</li>
</ul>
</div>
<span class="target" id="index-71"></span></dd></dl>
<dl class="method">
<dt id="object.__repr__">
<code class="descclassname">object.</code><code class="descname">__repr__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__repr__" title="本定義的永久連結">¶</a></dt>
<dd><p>Called by the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> built-in function to compute the 「official」 string
representation of an object. If at all possible, this should look like a
valid Python expression that could be used to recreate an object with the
same value (given an appropriate environment). If this is not possible, a
string of the form <code class="docutils literal notranslate"><span class="pre"><...some</span> <span class="pre">useful</span> <span class="pre">description...></span></code> should be returned.
The return value must be a string object. If a class defines <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>
but not <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> is also used when an
「informal」 string representation of instances of that class is required.</p>
<p>This is typically used for debugging, so it is important that the representation
is information-rich and unambiguous.</p>
<span class="target" id="index-72"></span></dd></dl>
<dl class="method">
<dt id="object.__str__">
<code class="descclassname">object.</code><code class="descname">__str__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__str__" title="本定義的永久連結">¶</a></dt>
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str(object)</span></code></a> and the built-in functions
<a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> and <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> to compute the 「informal」 or nicely
printable string representation of an object. The return value must be a
<a class="reference internal" href="../library/stdtypes.html#textseq"><span class="std std-ref">string</span></a> object.</p>
<p>This method differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__repr__()</span></code></a> in that there is no
expectation that <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> return a valid Python expression: a more
convenient or concise representation can be used.</p>
<p>The default implementation defined by the built-in type <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>
calls <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__repr__()</span></code></a>.</p>
</dd></dl>
<dl class="method">
<dt id="object.__bytes__">
<code class="descclassname">object.</code><code class="descname">__bytes__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bytes__" title="本定義的永久連結">¶</a></dt>
<dd><p id="index-73">Called by <a class="reference internal" href="../library/functions.html#func-bytes"><span class="std std-ref">bytes</span></a> to compute a byte-string representation
of an object. This should return a <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> object.</p>
<span class="target" id="index-74"></span></dd></dl>