forked from flaggo/python3-source-code-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobject.html
More file actions
763 lines (457 loc) · 53 KB
/
object.html
File metadata and controls
763 lines (457 loc) · 53 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
<!DOCTYPE HTML>
<html lang="zh-hans" >
<head>
<meta charset="UTF-8">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Python 对象初探 · Python 3 源码分析</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="description" content="">
<meta name="generator" content="GitBook 3.2.3">
<meta name="author" content="Prodesire">
<link rel="stylesheet" href="../gitbook/style.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-search-plus/search.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-splitter/splitter.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-tbfed-pagefooter/footer.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-prism/prism-okaidia.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-page-toc-button/plugin.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-back-to-top-button/plugin.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-highlight/website.css">
<link rel="stylesheet" href="../gitbook/gitbook-plugin-fontsettings/website.css">
<meta name="HandheldFriendly" content="true"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="../gitbook/images/apple-touch-icon-precomposed-152.png">
<link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">
<link rel="next" href="long-object.html" />
<link rel="prev" href="../preface/modify-code.html" />
<style>
@media only screen and (max-width: 640px) {
.book-header .hidden-mobile {
display: none;
}
}
</style>
<script>
window["gitbook-plugin-github-buttons"] = {"repo":"flaggo/python3-source-code-analysis","types":["star"],"size":"small"};
</script>
</head>
<body>
<div class="book">
<div class="book-summary">
<div id="book-search-input" role="search">
<input type="text" placeholder="输入并搜索" />
</div>
<nav role="navigation">
<ul class="summary">
<li>
<a href="https://github.com/flaggo/python3-source-code-analysis" target="_blank" class="custom-link">主页</a>
</li>
<li class="divider"></li>
<li class="header">第 1 部分:序章</li>
<li class="chapter " data-level="1.1" data-path="../">
<a href="../">
<b>1.1.</b>
前言
</a>
</li>
<li class="chapter " data-level="1.2" data-path="../preface/code-organization.html">
<a href="../preface/code-organization.html">
<b>1.2.</b>
Python 源代码的组织
</a>
</li>
<li class="chapter " data-level="1.3" data-path="../preface/windows-build.html">
<a href="../preface/windows-build.html">
<b>1.3.</b>
Windows 环境下编译 Python
</a>
</li>
<li class="chapter " data-level="1.4" data-path="../preface/unix-linux-build.html">
<a href="../preface/unix-linux-build.html">
<b>1.4.</b>
UNIX/Linux 环境下编译 Python
</a>
</li>
<li class="chapter " data-level="1.5" data-path="../preface/modify-code.html">
<a href="../preface/modify-code.html">
<b>1.5.</b>
修改 Python 源码
</a>
</li>
<li class="header">第 2 部分:Python 内建对象</li>
<li class="chapter active" data-level="2.1" data-path="object.html">
<a href="object.html">
<b>2.1.</b>
Python 对象初探
</a>
</li>
<li class="chapter " data-level="2.2" data-path="long-object.html">
<a href="long-object.html">
<b>2.2.</b>
Python 整数对象
</a>
</li>
<li class="chapter " data-level="2.3" data-path="string-object.html">
<a href="string-object.html">
<b>2.3.</b>
Python 字符串 对象
</a>
</li>
<li class="chapter " data-level="2.4" data-path="list-object.html">
<a href="list-object.html">
<b>2.4.</b>
Python List 对象
</a>
</li>
<li class="chapter " data-level="2.5" data-path="dict-object.html">
<a href="dict-object.html">
<b>2.5.</b>
Python Dict 对象
</a>
</li>
<li class="chapter " data-level="2.6" data-path="set-object.html">
<a href="set-object.html">
<b>2.6.</b>
Python Set 对象
</a>
</li>
<li class="chapter " data-level="2.7" data-path="simple-implementation.html">
<a href="simple-implementation.html">
<b>2.7.</b>
实现简版 Python
</a>
</li>
<li class="header">第 3 部分:Python 虚拟机</li>
<li class="divider"></li>
<li>
<a href="https://www.gitbook.com" target="blank" class="gitbook-link">
本书使用 GitBook 发布
</a>
</li>
</ul>
</nav>
</div>
<div class="book-body">
<div class="body-inner">
<div class="book-header" role="navigation">
<!-- Title -->
<h1>
<i class="fa fa-circle-o-notch fa-spin"></i>
<a href=".." >Python 对象初探</a>
</h1>
</div>
<div class="page-wrapper" tabindex="-1" role="main">
<div class="page-inner">
<div id="book-search-results">
<div class="search-noresults">
<section class="normal markdown-section">
<h1 id="python-对象初探">Python 对象初探</h1>
<p>在Python的世界一切皆对象,不论是整数,还是字符串,甚至连类型、函数等都是一种对象。</p>
<h2 id="对象的分类">对象的分类</h2>
<p>以下是Python对象的大致的一个分类</p>
<ul>
<li>Fundamental 对象: 类型对象</li>
<li>Numeric 对象: 数值对象</li>
<li>Sequence 对象: 容纳其他对象的序列集合对象</li>
<li>Mapping 对象: 类似 C++中的 map 的关联对象</li>
<li>Internal 对象: Python 虚拟机在运行时内部使用的对象</li>
</ul>
<p><img src="object_category.jpg" alt="object category"></p>
<h2 id="对象机制的基石-pyobject">对象机制的基石 PyObject</h2>
<p>对于初学者来说这么多类型的对象怎么学?别着急,我们后续章节会解答。</p>
<p>在开始我们的学习之旅之前,我们要先认识一个结构体<strong>PyObject</strong>,可以说Python的对象机制就是基于<strong>PyObject</strong>拓展开来的,所以我们先看看<strong>PyObject</strong> 到底长什么样。</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L106" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token macro property">#<span class="token directive keyword">define</span> _PyObject_HEAD_EXTRA \
struct _object *_ob_next; \
struct _object *_ob_prev;</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> _object <span class="token punctuation">{</span>
_PyObject_HEAD_EXTRA <span class="token comment">// 双向链表 垃圾回收 需要用到</span>
Py_ssize_t ob_refcnt<span class="token punctuation">;</span> <span class="token comment">// 引用计数</span>
<span class="token keyword">struct</span> _typeobject <span class="token operator">*</span>ob_type<span class="token punctuation">;</span> <span class="token comment">// 指向类型对象的指针,决定了对象的类型</span>
<span class="token punctuation">}</span> PyObject<span class="token punctuation">;</span>
</code></pre>
<p>Python中的所有对象都拥有一些相同的内容,而这些内容就定义在<strong>PyObject</strong>中,</p>
<p><strong>PyObject</strong> 包含 一个用于垃圾回收的双向链表,一个引用计数变量 <code>ob_refcnt</code> 和 一个类型对象指针<code>ob_type</code></p>
<p><img src="PyObject.jpg" alt="PyObject"></p>
<h2 id="定长对象与变长对象">定长对象与变长对象</h2>
<p>Python对象除了前面提到的那种分类方法外,还可以分为定长对象和变长对象这两种形式。</p>
<p>变长对象都拥有一个相同的内容 <strong>PyVarObject</strong>,而 <strong>PyVarObject</strong>也是基于<strong>PyObject</strong>扩展的。</p>
<p>从代码中可以看出<strong>PyVarObject</strong>比<strong>PyObject</strong>多出了一个用于存储元素个数的变量<em>ob_size</em>。</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L106" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> _object <span class="token punctuation">{</span>
_PyObject_HEAD_EXTRA
Py_ssize_t ob_refcnt<span class="token punctuation">;</span>
<span class="token keyword">struct</span> _typeobject <span class="token operator">*</span>ob_type<span class="token punctuation">;</span>
<span class="token punctuation">}</span> PyObject<span class="token punctuation">;</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> <span class="token punctuation">{</span>
PyObject ob_base<span class="token punctuation">;</span>
Py_ssize_t ob_size<span class="token punctuation">;</span> <span class="token comment">/* Number of items in variable part */</span>
<span class="token punctuation">}</span> PyVarObject<span class="token punctuation">;</span>
</code></pre>
<p><img src="PyVarObject.jpg" alt="PyVarObject"></p>
<h2 id="类型对象">类型对象</h2>
<p>前面我们提到了<strong>PyObject</strong> 的 对象类型指针<code>struct _typeobject *ob_type</code>,它指向的类型对象就决定了一个对象是什么类型的。</p>
<p>这是一个非常重要的结构体,它不仅仅决定了一个对象的类型,还包含大量的<code>元信息</code>,
包括创建对象需要分配多少内存,对象都支持哪些操作等等。</p>
<p>接下来我们看一下<code>struct _typeobject</code>代码</p>
<p>在 <strong>PyTypeObject</strong> 的定义中包含许多信息,主要分类以下几类:</p>
<ul>
<li>类型名, tp_name, 主要用于 Python 内部调试用</li>
<li>创建该类型对象时分配的空间大小信息,即 <code>tp_basicsize</code> 和 <code>tp_itemsize</code></li>
<li>与该类型对象相关的操作信息(如 <code>tp_print</code> 这样的函数指针)</li>
<li>一些对象属性</li>
</ul>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L346" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> _typeobject <span class="token punctuation">{</span>
PyObject_VAR_HEAD
<span class="token keyword">const</span> <span class="token keyword">char</span> <span class="token operator">*</span>tp_name<span class="token punctuation">;</span> <span class="token comment">/* For printing, in format "<module>.<name>" */</span> <span class="token comment">// 类型名</span>
Py_ssize_t tp_basicsize<span class="token punctuation">,</span> tp_itemsize<span class="token punctuation">;</span> <span class="token comment">/* For allocation */</span>
<span class="token comment">// 创建该类型对象分配的内存空间大小</span>
<span class="token comment">// 一堆方法定义,函数和指针</span>
<span class="token comment">/* Methods to implement standard operations */</span>
destructor tp_dealloc<span class="token punctuation">;</span>
printfunc tp_print<span class="token punctuation">;</span>
getattrfunc tp_getattr<span class="token punctuation">;</span>
setattrfunc tp_setattr<span class="token punctuation">;</span>
PyAsyncMethods <span class="token operator">*</span>tp_as_async<span class="token punctuation">;</span> <span class="token comment">/* formerly known as tp_compare (Python 2)
or tp_reserved (Python 3) */</span>
reprfunc tp_repr<span class="token punctuation">;</span>
<span class="token comment">/* Method suites for standard classes */</span>
<span class="token comment">// 标准类方法集</span>
PyNumberMethods <span class="token operator">*</span>tp_as_number<span class="token punctuation">;</span> <span class="token comment">// 数值对象操作</span>
PySequenceMethods <span class="token operator">*</span>tp_as_sequence<span class="token punctuation">;</span> <span class="token comment">// 序列对象操作</span>
PyMappingMethods <span class="token operator">*</span>tp_as_mapping<span class="token punctuation">;</span> <span class="token comment">// 字典对象操作</span>
<span class="token comment">// 更多标准操作</span>
<span class="token comment">/* More standard operations (here for binary compatibility) */</span>
hashfunc tp_hash<span class="token punctuation">;</span>
ternaryfunc tp_call<span class="token punctuation">;</span>
reprfunc tp_str<span class="token punctuation">;</span>
getattrofunc tp_getattro<span class="token punctuation">;</span>
setattrofunc tp_setattro<span class="token punctuation">;</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span> PyTypeObject<span class="token punctuation">;</span>
</code></pre>
<h2 id="类型的类型">类型的类型</h2>
<p>在 <strong>PyTypeObjet</strong> 定义开始有一个宏<code>PyOject_VAR_HEAD</code>,查看源码可知 <strong>PyTypeObjet</strong> 是一个变长对象</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L98" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token macro property">#<span class="token directive keyword">define</span> PyObject_VAR_HEAD PyVarObject ob_base;</span>
</code></pre>
<p>对象的类型是由该对象指向的 类型对象 决定的,那么类型对象的类型是由谁决定的呢?
对于其他对象,可以通过与其关联的类型对象确定其类型,那么通过什么来确定一个对象是类型对象呢?
答案就是 <code>PyType_Type</code></p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Objects/typeobject.c#L3540" target="_blank">Objects/typeobject.c</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Objects/typeobject.c</span>
PyTypeObject PyType_Type <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token function">PyVarObject_HEAD_INIT</span><span class="token punctuation">(</span><span class="token operator">&</span>PyType_Type<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
<span class="token string">"type"</span><span class="token punctuation">,</span> <span class="token comment">/* tp_name */</span>
<span class="token keyword">sizeof</span><span class="token punctuation">(</span>PyHeapTypeObject<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">/* tp_basicsize */</span>
<span class="token keyword">sizeof</span><span class="token punctuation">(</span>PyMemberDef<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">/* tp_itemsize */</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
<p><code>PyType_Type</code> 在类型机制中至关重要,所有用户自定义 <code>class</code> 所
对应的 <code>PyTypeObject</code> 对象都是通过 <code>PyType_Type</code>创建的</p>
<p>接下来我们看 <code>PyLong_Type</code> 是怎么与 <code>PyType_Type</code> 建立联系的。
前面提到,在Python中,每一个对象都将自己的引用计数、类型信息保存在开始的部分中。
为了方便对这部分内存初始化,Python中提供了几个有用的宏:</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L69" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token macro property">#<span class="token directive keyword">ifdef</span> Py_TRACE_REFS</span>
<span class="token macro property">#<span class="token directive keyword">define</span> _PyObject_EXTRA_INIT 0, 0,</span>
<span class="token macro property">#<span class="token directive keyword">else</span></span>
<span class="token macro property">#<span class="token directive keyword">define</span> _PyObject_EXTRA_INIT</span>
<span class="token macro property">#<span class="token directive keyword">endif</span></span>
<span class="token macro property">#<span class="token directive keyword">define</span> PyObject_HEAD_INIT(type) \
{ _PyObject_EXTRA_INIT \
1, type },</span>
</code></pre>
<p>这些宏在各种内建类型对象的初始化中被大量使用。
以<code>PyLong_Type</code>为例,可以清晰的看到一般的类型对象和<code>PyType_Type</code>之间的关系</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Objects/longobject.c#L5379" target="_blank">Objects/longobject.c</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Objects/longobject.c</span>
PyTypeObject PyLong_Type <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token function">PyVarObject_HEAD_INIT</span><span class="token punctuation">(</span><span class="token operator">&</span>PyType_Type<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
<span class="token string">"int"</span><span class="token punctuation">,</span> <span class="token comment">/* tp_name */</span>
<span class="token function">offsetof</span><span class="token punctuation">(</span>PyLongObject<span class="token punctuation">,</span> ob_digit<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">/* tp_basicsize */</span>
<span class="token keyword">sizeof</span><span class="token punctuation">(</span>digit<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">/* tp_itemsize */</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
<p>下图是对象运行时的图像表现</p>
<p><img src="object_runtime_relation.jpg" alt=""></p>
<h2 id="对象的创建">对象的创建</h2>
<p>Python创建对象有两种方式</p>
<h3 id="范型api-或称为-aol-abstract-object-layer">范型API 或称为 AOL (Abstract Object Layer)</h3>
<p>这类API通常形如<code>PyObject_XXX</code>这样的形式。可以应用在任何Python对象上,
如<code>PyObject_Print</code>。创建一个整数对象的方式</p>
<pre class="language-"><code class="lang-c">PyObject<span class="token operator">*</span> longobj <span class="token operator">=</span> <span class="token function">PyObject_New</span><span class="token punctuation">(</span>Pyobject<span class="token punctuation">,</span> <span class="token operator">&</span>PyLong_Type<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
<h3 id="与类型相关的api-或称为-col-concrete-object-layer">与类型相关的API 或称为 COL (Concrete Object Layer)</h3>
<p>这类API 通常只能作用于某一种类型的对象上,对于每一种内建对象
Python都提供了这样一组API。例如整数对象,我们可以利用如下的API创建</p>
<pre class="language-"><code class="lang-c">PyObject <span class="token operator">*</span>longObj <span class="token operator">=</span> <span class="token function">PyLong_FromLong</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
<h2 id="对象的行为">对象的行为</h2>
<p>在 <strong>PyTypeObject</strong> 中定义了大量的函数指针。这些函数指针可以视为类型对象中
所定义的操作,这些操作直接决定着一个对象在运行时所表现出的行为,比如 <strong>PyTypeObject</strong> 中的 <code>tp_hash</code> 指明了该类型对象如何生成其<code>hash</code>值。</p>
<p>在<strong>PyTypeObject</strong>的代码中,我们还可以看到非常重要的三组操作族</p>
<ul>
<li><code>PyNumberMethods *tp_as_number</code></li>
<li><code>PySequenceMethods *tp_as_sequence</code></li>
<li><code>PyMappingMethods *tp_as_mapping</code></li>
</ul>
<p><strong>PySequenceMethods</strong> 的代码如下</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L240" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token keyword">typedef</span> PyObject <span class="token operator">*</span> <span class="token punctuation">(</span><span class="token operator">*</span>binaryfunc<span class="token punctuation">)</span><span class="token punctuation">(</span>PyObject <span class="token operator">*</span><span class="token punctuation">,</span> PyObject <span class="token operator">*</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">typedef</span> <span class="token keyword">struct</span> <span class="token punctuation">{</span>
binaryfunc nb_matrix_multiply<span class="token punctuation">;</span>
binaryfunc nb_inplace_matrix_multiply<span class="token punctuation">;</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span> PyNumberMethods<span class="token punctuation">;</span>
</code></pre>
<p><strong>PyNumberMethods</strong> 定义了一个数值对象该支持的操作。一个数值对象如 整数对象,那么它的类型对象 <code>PyLong_Type</code>中<code>tp_as_number.nb_add</code>
就指定了它进行加法操作时的具体行为。</p>
<p>在以下代码中可以看出<code>PyLong_Type</code>中的<code>tp_as_number</code>项指向的是<code>long_as_number</code></p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Objects/longobject.c#L5342" target="_blank">Objects/longobject.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Objects/longobject.c</span>
<span class="token keyword">static</span> PyNumberMethods long_as_number <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token punctuation">(</span>binaryfunc<span class="token punctuation">)</span>long_add<span class="token punctuation">,</span> <span class="token comment">/*nb_add*/</span>
<span class="token punctuation">(</span>binaryfunc<span class="token punctuation">)</span>long_sub<span class="token punctuation">,</span> <span class="token comment">/*nb_subtract*/</span>
<span class="token punctuation">(</span>binaryfunc<span class="token punctuation">)</span>long_mul<span class="token punctuation">,</span> <span class="token comment">/*nb_multiply*/</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
PyTypeObject PyLong_Type <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token function">PyVarObject_HEAD_INIT</span><span class="token punctuation">(</span><span class="token operator">&</span>PyType_Type<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
<span class="token string">"int"</span><span class="token punctuation">,</span> <span class="token comment">/* tp_name */</span>
<span class="token function">offsetof</span><span class="token punctuation">(</span>PyLongObject<span class="token punctuation">,</span> ob_digit<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">/* tp_basicsize */</span>
<span class="token keyword">sizeof</span><span class="token punctuation">(</span>digit<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token comment">/* tp_itemsize */</span>
long_dealloc<span class="token punctuation">,</span> <span class="token comment">/* tp_dealloc */</span>
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">/* tp_print */</span>
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">/* tp_getattr */</span>
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">/* tp_setattr */</span>
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">/* tp_reserved */</span>
long_to_decimal_string<span class="token punctuation">,</span> <span class="token comment">/* tp_repr */</span>
<span class="token operator">&</span>long_as_number<span class="token punctuation">,</span> <span class="token comment">/* tp_as_number */</span>
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">/* tp_as_sequence */</span>
<span class="token number">0</span><span class="token punctuation">,</span> <span class="token comment">/* tp_as_mapping */</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
<p><code>PySequenceMethods *tp_as_sequence</code> 和 <code>PyMappingMethods *tp_as_mapping</code>的分析与<code>PyNumberMethods *tp_as_number</code> 相同,大家可以自行查阅源码</p>
<h2 id="对象的多态性">对象的多态性</h2>
<p>Python创建一个对象比如 <strong>PyLongObject</strong> 时,会分配内存进行初始化,然后
Python内部会用 <code>PyObject*</code> 变量来维护这个对象,其他对象也与此类似</p>
<p>所以在 Python 内部各个函数之间传递的都是一种范型指针 <code>PyObject*</code>
我们不知道这个指针所指的对象是什么类型,只能通过所指对象的 <code>ob_type</code> 域
动态进行判断,而Python正是通过 <code>ob_type</code> 实现了多态机制</p>
<p>考虑以下的 py_hash 函数</p>
<pre class="language-"><code class="lang-c">Py_hash_t
<span class="token function">calc_hash</span><span class="token punctuation">(</span>PyObject<span class="token operator">*</span> object<span class="token punctuation">)</span>
<span class="token punctuation">{</span>
Py_hash_t hash <span class="token operator">=</span> object<span class="token operator">-></span>ob_type<span class="token operator">-></span><span class="token function">tp_hash</span><span class="token punctuation">(</span>object<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> hash<span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre>
<p>如果传递给 calc_hash 函数的指针是一个 <code>PyLongObject*</code>,那么它会调用 PyLongObject 对象对应的类型对象中定义的 hash操作<code>tp_hash</code>,<code>tp_hash</code>可以在**PyTypeObject中找到,
而具体赋值绑定我们可以在 <code>PyLong_Type</code> 初始化代码中看到绑定的是<code>long_hash</code>函数</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Objects/longobject.c#L5379" target="_blank">Objects/longobject.c</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Objects/longobject.c</span>
PyTypeObject PyLong_Type <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token function">PyVarObject_HEAD_INIT</span><span class="token punctuation">(</span><span class="token operator">&</span>PyType_Type<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
<span class="token string">"int"</span><span class="token punctuation">,</span> <span class="token comment">/* tp_name */</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">(</span>hashfunc<span class="token punctuation">)</span>long_hash<span class="token punctuation">,</span> <span class="token comment">/* tp_hash */</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
<p>如果指针是一个 <code>PyUnicodeObject*</code>,那么就会调用 PyUnicodeObject 对象对应的类型对象中定义的输出操作,查看源码可以看到 实际绑定的是 <code>unicode_hash</code>函数</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Objects/unicodeobject.c#L15066" target="_blank">Objects/unicodeobject.c</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Objects/unicodeobject.c</span>
PyTypeObject PyUnicode_Type <span class="token operator">=</span> <span class="token punctuation">{</span>
<span class="token function">PyVarObject_HEAD_INIT</span><span class="token punctuation">(</span><span class="token operator">&</span>PyType_Type<span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span>
<span class="token string">"str"</span><span class="token punctuation">,</span> <span class="token comment">/* tp_name */</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">(</span>hashfunc<span class="token punctuation">)</span> unicode_hash<span class="token punctuation">,</span> <span class="token comment">/* tp_hash*/</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token punctuation">}</span><span class="token punctuation">;</span>
</code></pre>
<h2 id="引用计数">引用计数</h2>
<p>Python 通过引用计数来管理维护对象在内存中的存在与否</p>
<p>Python 中的每个东西都是一个对象, 都有<code>ob_refcnt</code> 变量,这个变量维护对象的引用计数,从而最终决定该对象的创建与销毁</p>
<p>在Python中,主要通过 <code>Py_INCREF(op)</code>与<code>Py_DECREF(op)</code> 这两个宏
来增加和减少对一个对象的引用计数。当一个对象的引用计数减少到0之后,
<code>Py_DECREF</code>将调用该对象的<code>tp_dealloc</code>来释放对象所占用的内存和系统资源;</p>
<p>但这并不意味着最终一定会调用 <code>free</code> 释放内存空间。因为频繁的申请、释放内存会大大降低Python的执行效率。因此Python中大量采用了内存对象池的技术,使得对象释放的空间归还给内存池而不是直接<code>free</code>,后续使用可先从对象池中获取</p>
<p><code>源文件:</code><a href="https://github.com/python/cpython/blob/v3.7.0/Include/object.h#L777" target="_blank">Include/object.h</a></p>
<pre class="language-"><code class="lang-c"><span class="token comment">// Include/object.h</span>
<span class="token macro property">#<span class="token directive keyword">define</span> _Py_NewReference(op) ( \
_Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
Py_REFCNT(op) = 1)</span>
<span class="token macro property">#<span class="token directive keyword">define</span> Py_INCREF(op) ( \
_Py_INC_REFTOTAL _Py_REF_DEBUG_COMMA \
((PyObject *)(op))->ob_refcnt++)</span>
<span class="token macro property">#<span class="token directive keyword">define</span> Py_DECREF(op) \
do { \
PyObject *_py_decref_tmp = (PyObject *)(op); \
if (_Py_DEC_REFTOTAL _Py_REF_DEBUG_COMMA \
--(_py_decref_tmp)->ob_refcnt != 0) \
_Py_CHECK_REFCNT(_py_decref_tmp) \
else \
_Py_Dealloc(_py_decref_tmp); \
} while (0)</span>
</code></pre>
<footer class="page-footer"><span class="copyright">Copyright © Prodesire 2018 all right reserved,powered by Gitbook</span><span class="footer-modification">该文件修订时间:
2019-01-04 09:16:46
</span></footer>
</section>
</div>
<div class="search-results">
<div class="has-results">
<h1 class="search-results-title"><span class='search-results-count'></span> results matching "<span class='search-query'></span>"</h1>
<ul class="search-results-list"></ul>
</div>
<div class="no-results">
<h1 class="search-results-title">No results matching "<span class='search-query'></span>"</h1>
</div>
</div>
</div>
</div>
</div>
</div>
<a href="../preface/modify-code.html" class="navigation navigation-prev " aria-label="Previous page: 修改 Python 源码">
<i class="fa fa-angle-left"></i>
</a>
<a href="long-object.html" class="navigation navigation-next " aria-label="Next page: Python 整数对象">
<i class="fa fa-angle-right"></i>
</a>
</div>
<script>
var gitbook = gitbook || [];
gitbook.push(function() {
gitbook.page.hasChanged({"page":{"title":"Python 对象初探","level":"2.1","depth":1,"next":{"title":"Python 整数对象","level":"2.2","depth":1,"path":"objects/long-object.md","ref":"objects/long-object.md","articles":[]},"previous":{"title":"修改 Python 源码","level":"1.5","depth":1,"path":"preface/modify-code.md","ref":"preface/modify-code.md","articles":[]},"dir":"ltr"},"config":{"plugins":["-search","search-plus@^0.0.11","-sharing","sharing-plus","github@^2.0.0","github-buttons@2.1.0","edit-link@^2.0.2","splitter","tbfed-pagefooter","prism","page-toc-button","back-to-top-button"],"root":".","styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"pluginsConfig":{"tbfed-pagefooter":{"copyright":"Copyright © Prodesire 2018","modify_label":"该文件修订时间:","modify_format":"YYYY-MM-DD HH:mm:ss"},"prism":{"lang":{"console":"bash","shell":"bash"},"css":["prismjs/themes/prism-okaidia.css"]},"github":{"url":"https://github.com/flaggo/python3-source-code-analysis"},"splitter":{},"sharing-plus":{"qq":false,"all":["facebook","google","twitter","instapaper","linkedin","pocket","stumbleupon"],"douban":false,"facebook":true,"weibo":false,"instapaper":false,"whatsapp":false,"hatenaBookmark":false,"twitter":true,"messenger":false,"line":false,"vk":false,"pocket":true,"google":false,"viber":false,"stumbleupon":false,"qzone":false,"linkedin":false},"lunr":{"maxIndexSize":1000000,"ignoreSpecialCharacters":false},"fontsettings":{"theme":"white","family":"sans","size":2},"highlight":{},"anchor-navigation-ex":{"isRewritePageTitle":false,"tocLevel1Icon":"fa fa-hand-o-right","tocLevel2Icon":"fa fa-hand-o-right","tocLevel3Icon":"fa fa-hand-o-right"},"page-toc-button":{},"back-to-top-button":{},"github-buttons":{"repo":"flaggo/python3-source-code-analysis","types":["star"],"size":"small"},"sharing":{"weibo":true,"douban":true,"linkedin":true,"facebook":true,"google":true,"twitter":true,"all":["weibo","douban","linkedin","facebook","google","twitter"]},"edit-link":{"label":"编辑此页面","base":"https://github.com/flaggo/python3-source-code-analysis/edit/master"},"theme-default":{"styles":{"website":"styles/website.css","pdf":"styles/pdf.css","epub":"styles/epub.css","mobi":"styles/mobi.css","ebook":"styles/ebook.css","print":"styles/print.css"},"showLevel":true},"search-plus":{}},"theme":"default","author":"Prodesire","pdf":{"pageNumbers":true,"fontSize":12,"fontFamily":"Arial","paperSize":"a4","chapterMark":"pagebreak","pageBreaksBefore":"/","margin":{"right":62,"left":62,"top":56,"bottom":56}},"structure":{"langs":"LANGS.md","readme":"README.md","glossary":"GLOSSARY.md","summary":"SUMMARY.md"},"variables":{},"title":"Python 3 源码分析","language":"zh-hans","output.name":"site","links":{"sidebar":{"主页":"https://github.com/flaggo/python3-source-code-analysis"}},"gitbook":"3.2.3","description":"致力于分析Python 3.7.0 的源码实现"},"file":{"path":"objects/object.md","mtime":"2019-01-04T01:16:46.950Z","type":"markdown"},"gitbook":{"version":"3.2.3","time":"2019-01-04T01:17:55.427Z"},"basePath":"..","book":{"language":""}});
});
</script>
</div>
<script src="../gitbook/gitbook.js"></script>
<script src="../gitbook/theme.js"></script>
<script src="../gitbook/gitbook-plugin-search-plus/jquery.mark.min.js"></script>
<script src="../gitbook/gitbook-plugin-search-plus/search.js"></script>
<script src="../gitbook/gitbook-plugin-sharing-plus/buttons.js"></script>
<script src="../gitbook/gitbook-plugin-github/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-github-buttons/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-edit-link/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-splitter/splitter.js"></script>
<script src="../gitbook/gitbook-plugin-page-toc-button/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-back-to-top-button/plugin.js"></script>
<script src="../gitbook/gitbook-plugin-lunr/lunr.min.js"></script>
<script src="../gitbook/gitbook-plugin-lunr/search-lunr.js"></script>
<script src="../gitbook/gitbook-plugin-fontsettings/fontsettings.js"></script>
</body>
</html>