-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
506 lines (373 loc) · 22.6 KB
/
index.html
File metadata and controls
506 lines (373 loc) · 22.6 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
<!doctype html>
<html lang="en-us">
<head>
<title>Python中的魔法方法 // sin-coder</title>
<meta charset="utf-8" />
<meta name="generator" content="Hugo 0.59.1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="csuyzz" />
<meta name="description" content="" />
<link rel="stylesheet" href="https://sin-coder.github.io/css/main.min.f90f5edd436ec7b74ad05479a05705770306911f721193e7845948fb07fe1335.css" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Python中的魔法方法"/>
<meta name="twitter:description" content="Python中的魔法方法 一、什么是Python的魔法方法? 魔法方法就是Python的内置方法,不需要主动调用,存在的目的就是给Python的解释器进行调用,几乎每个
魔法方法都有一个对应的内置函数或者运算符,它们经常是使用两个下划线包围来命名的,最为常见的就是
__ init __方法了。总的来说魔法方法就是让我们对类添加魔法的特殊方法(说跟没有说一样)
二、常见的魔法方法 1.构造方法 最为常用的魔法方法就是__ init __方法了,我们可以使用它来指明一个对象初始化的行为。实际上,
当我们再实例化对象时,__ init __方法并不是第一个被调用的方法。事实上应该是new方法,当这个对
象的生命周期结束的时候,__ del __方法会被调用。下面具体阐述
(1)__ new __(cls,[....])
__ new __是对象实例化第一个调用的方法,它只取下cls参数并把其他的参数传递给init方法,它很少使用
(2)__ init __(self,[....])
这是类的初始化方法,它能获取任何传给构造器的参数,这个方法在类的定义中使用到的是最多的
(3)__ del __(self)
new和init都是对象的构造器,__ del __是对象的销毁器,它不是实现了语句del x,而是定义了对象被垃圾
回收时的行为。当对象需要销毁做一些处理的时候这个方法很有用,比如socket对象、文件对象。但是当
Python解释器退出但对象仍然存活的时候,__ del __并不会执行,所以要及时地手工清理对象
下面是一个示例:
from os.path import join class FileObject: #文件对象的装饰类,用来保证文件被删除时能够正确关闭 def __init__(self,filepath = '~',filename = 'sample.txt'): self.file = open(join(filepath,filename),'r+') def __del__(self): self.file.close() del self.file 2."/>
<meta property="og:title" content="Python中的魔法方法" />
<meta property="og:description" content="Python中的魔法方法 一、什么是Python的魔法方法? 魔法方法就是Python的内置方法,不需要主动调用,存在的目的就是给Python的解释器进行调用,几乎每个
魔法方法都有一个对应的内置函数或者运算符,它们经常是使用两个下划线包围来命名的,最为常见的就是
__ init __方法了。总的来说魔法方法就是让我们对类添加魔法的特殊方法(说跟没有说一样)
二、常见的魔法方法 1.构造方法 最为常用的魔法方法就是__ init __方法了,我们可以使用它来指明一个对象初始化的行为。实际上,
当我们再实例化对象时,__ init __方法并不是第一个被调用的方法。事实上应该是new方法,当这个对
象的生命周期结束的时候,__ del __方法会被调用。下面具体阐述
(1)__ new __(cls,[....])
__ new __是对象实例化第一个调用的方法,它只取下cls参数并把其他的参数传递给init方法,它很少使用
(2)__ init __(self,[....])
这是类的初始化方法,它能获取任何传给构造器的参数,这个方法在类的定义中使用到的是最多的
(3)__ del __(self)
new和init都是对象的构造器,__ del __是对象的销毁器,它不是实现了语句del x,而是定义了对象被垃圾
回收时的行为。当对象需要销毁做一些处理的时候这个方法很有用,比如socket对象、文件对象。但是当
Python解释器退出但对象仍然存活的时候,__ del __并不会执行,所以要及时地手工清理对象
下面是一个示例:
from os.path import join class FileObject: #文件对象的装饰类,用来保证文件被删除时能够正确关闭 def __init__(self,filepath = '~',filename = 'sample.txt'): self.file = open(join(filepath,filename),'r+') def __del__(self): self.file.close() del self.file 2." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://sin-coder.github.io/program/magic/" />
<meta property="article:published_time" content="2019-12-24T21:14:28+08:00" />
<meta property="article:modified_time" content="2019-12-24T21:14:28+08:00" />
</head>
<body>
<header class="app-header">
<a href="https://sin-coder.github.io"><img class="app-header-avatar" src="/cat.jpg" alt="csuyzz" /></a>
<h1>sin-coder</h1>
<p>I always remember that 'Talk is cheap,show me the code'</p>
<div class="app-header-social">
<a target="_blank" href="https://github.com/sin-coder" rel="noreferrer noopener"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-github">
<title>github</title>
<path d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"></path>
</svg></a>
<a target="_blank" href="mailto:csuyzz@foxmail.com" rel="noreferrer noopener"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-mail">
<title>mail</title>
<path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"></path><polyline points="22,6 12,13 2,6"></polyline>
</svg></a>
<a target="_blank" href="https://cn.linkedin.com/in/csuyzz" rel="noreferrer noopener"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-linkedin">
<title>linkedin</title>
<path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"></path><rect x="2" y="9" width="4" height="12"></rect><circle cx="4" cy="4" r="2"></circle>
</svg></a>
<a target="_blank" href="https://twitter.com/csuyzz1" rel="noreferrer noopener"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-twitter">
<title>twitter</title>
<path d="M23 3a10.9 10.9 0 0 1-3.14 1.53 4.48 4.48 0 0 0-7.86 3v1A10.66 10.66 0 0 1 3 4s-4 9 5 13a11.64 11.64 0 0 1-7 2c9 5 20 0 20-11.5a4.5 4.5 0 0 0-.08-.83A7.72 7.72 0 0 0 23 3z"></path>
</svg></a>
</div>
<h3><a href="/" title="首页">首页</a></h3>
<h3><a href="/category/content/" title="首页">分类目录</a></h3>
<h3><a href="/personal/introduce/" title="首页">个人简介</a></h3>
</header>
<main class="app-container">
<article class="post">
<header class="post-header">
<h1 class ="post-title">Python中的魔法方法</h1>
<div class="post-meta">
<div>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-calendar">
<title>calendar</title>
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line>
</svg>
Dec 24, 2019
</div>
<div>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-clock">
<title>clock</title>
<circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline>
</svg>
3 min read
</div><div>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tag">
<title>tag</title>
<path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path><line x1="7" y1="7" x2="7" y2="7"></line>
</svg>
<a class="tag" href="https://sin-coder.github.io/tags/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">编程语言</a><a class="tag" href="https://sin-coder.github.io/tags/python/">Python</a></div></div>
</header>
<div class="post-content">
<h2 id="python中的魔法方法">Python中的魔法方法</h2>
<hr />
<h3 id="一-什么是python的魔法方法">一、什么是Python的魔法方法?</h3>
<blockquote>
<p>魔法方法就是Python的内置方法,不需要主动调用,存在的目的就是给Python的解释器进行调用,几乎每个</p>
</blockquote>
<p>魔法方法都有一个对应的内置函数或者运算符,它们经常是使用两个下划线包围来命名的,最为常见的就是</p>
<p>__ init __方法了。总的来说魔法方法就是让我们对类添加<strong>魔法</strong>的特殊方法(说跟没有说一样)</p>
<h3 id="二-常见的魔法方法">二、常见的魔法方法</h3>
<h4 id="1-构造方法">1.构造方法</h4>
<blockquote>
<p>最为常用的魔法方法就是__ init __方法了,我们可以使用它来指明一个对象初始化的行为。实际上,</p>
</blockquote>
<p>当我们再实例化对象时,__ init __方法并不是第一个被调用的方法。事实上应该是new方法,当这个对</p>
<p>象的生命周期结束的时候,__ del __方法会被调用。下面具体阐述</p>
<blockquote>
<p><strong>(1)__ new __(cls,[....])</strong></p>
<p>__ new __是对象实例化第一个调用的方法,它只取下cls参数并把其他的参数传递给init方法,它很少使用</p>
<p><strong>(2)__ init __(self,[....])</strong></p>
<p>这是类的初始化方法,它能获取任何传给构造器的参数,这个方法在类的定义中使用到的是最多的</p>
<p><strong>(3)__ del __(self)</strong></p>
<p>new和init都是对象的构造器,__ del __是对象的销毁器,它不是实现了语句del x,而是定义了对象被垃圾</p>
</blockquote>
<p>回收时的行为。当对象需要销毁做一些处理的时候这个方法很有用,比如socket对象、文件对象。但是当</p>
<p>Python解释器退出但对象仍然存活的时候,__ del __并不会执行,所以要及时地手工清理对象</p>
<blockquote>
<p>下面是一个示例:</p>
</blockquote>
<pre><code class="language-python">from os.path import join
class FileObject:
#文件对象的装饰类,用来保证文件被删除时能够正确关闭
def __init__(self,filepath = '~',filename = 'sample.txt'):
self.file = open(join(filepath,filename),'r+')
def __del__(self):
self.file.close()
del self.file
</code></pre>
<h4 id="2-运算符">2.运算符</h4>
<blockquote>
<p><strong>(1)比较运算符</strong></p>
</blockquote>
<ul>
<li><p>__ eq __(self,other) : 定义等于操作符的行为</p></li>
<li><p>__ ne __(self,other) : 定义不等于操作符的行为</p></li>
<li><p>__ lt __(self,other) : 定义小于操作符的行为</p></li>
<li><p>__ gt __(self,other) : 定义大于操作符的行为</p></li>
<li><p>__ le __(self,other) : 定义小于等于操作符的行为</p></li>
<li><p>__ ge __(self,other) : 定义大于等于操作符的行为</p></li>
</ul>
<blockquote>
<p><strong>(2)一元操作符</strong></p>
</blockquote>
<ul>
<li><p>__ pos __(self) : 实现取正的操作</p></li>
<li><p>__ neg __(self) : 实现取负的操作</p></li>
<li><p>__ abs __(self) : 实现内建绝对值函数abs()的操作</p></li>
<li><p>__ invert __(self) : 实现取反的操作</p></li>
<li><p>__ round __(self) : 实现内建函数round()的操作</p></li>
<li><p>__ floor __(self) : 实现math.floor()函数的操作</p></li>
<li><p>__ ceil __(self) : 实现math.ceil()函数的操作</p></li>
<li><p>__ trunc __(self) : 实现math.trunc()函数的操作,距离零最近的整数</p></li>
</ul>
<blockquote>
<p><strong>(3)算数操作符</strong></p>
</blockquote>
<ul>
<li><p>__ add __(self,other) : 实现加法的操作</p></li>
<li><p>__ sub __(self,other) : 实现减法的操作</p></li>
<li><p>__ mul __(self,other) : 实现乘法的操作</p></li>
<li><p>__ floordiv __(self,other) : 实现 // 操作符的整数除法</p></li>
<li><p>__ div __(self,other) : 实现使用 / 操作符的除法</p></li>
<li><p>__ mod __(self,other) : 实现取余函数的操作</p></li>
<li><p>__ pow __(self,other) : 实现pow()函数的操作</p></li>
<li><p>__ lshift __(self,other) : 实现左移位运算符</p></li>
<li><p>__ rshift __(self,other) : 实现右移运算符</p></li>
<li><p>__ and __(self,other) : 实现按位与运算符</p></li>
<li><p>__ or __(self,other) : 实现按位或运算符</p></li>
<li><p>__ xor __(self,other) : 实现按位异或运算符</p></li>
</ul>
<blockquote>
<p><strong>(4)类型转换操作符</strong></p>
</blockquote>
<ul>
<li><p>__ int__(self) : 实现到int的类型转换</p></li>
<li><p>__ float__(self) : 实现到float的类型转换</p></li>
<li><p>__ complex__(self) : 实现到complex的类型转换</p></li>
<li><p>__ oct__(self) : 实现到八进制数转换</p></li>
<li><p>__ hex__(self) : 实现到十六进制数转换</p></li>
</ul>
<h4 id="3-类的表示">3.类的表示</h4>
<blockquote>
<p>使用字符串来表示类是一个相当有用的特性,在Python中有一些内建方法可以返回类的表示,也有</p>
</blockquote>
<p>一系列魔性方法可以用来自定义在使用这些内建函数时类的行为</p>
<ul>
<li><p>__ str __(self): 定义对类的实例调用str()的行为</p></li>
<li><p>__ repr__(self):与str()方法最大的区别就是str()的输出人类可读,repr()机器可读</p></li>
<li><p>__ unicode __(self):定义对类的实例调用unicode()的行为,返回unicode字符串</p></li>
<li><p>__ formate __(self): 定义当类的实例用于新式字符串格式化时的行为</p></li>
<li><p>__ hash __(self): 定义当类的实例调用hash()时的行为,它必须返回一个整数,结果用于字典中键的快速比较</p></li>
<li><p>__ nonzero __(self): 定义当类的实例调用bool()时的行为</p></li>
<li><p>__ dir __(self): 定义当类的实例调用dir()时的行为,这个方法会向调用者返回一个属性列表</p></li>
</ul>
<h4 id="4-访问控制">4.访问控制</h4>
<blockquote>
<p>Python不是通过显式定义的字段和方法修改器,而是通过魔法方法实现了一系列的封装</p>
</blockquote>
<ul>
<li>__ getattr __(self,name):当用户试图访问一个根本不存在的属性时,用户可以通过这个模型方法来定义类</li>
</ul>
<blockquote>
<p>的具体行为</p>
</blockquote>
<ul>
<li>__ setattr __(self,name,value): 允许用户自己定义某个属性的赋值行为,不管这个属性是否存在</li>
<li>__ delattr __ (self,name) :处理删除属性时的行为,使用时方式产生无限递归</li>
</ul>
<h4 id="5-自定义序列">5.自定义序列</h4>
<blockquote>
<p>有许多方法可以让自定义的Python类表现的像内建序列类型(字典、元组、列表、字符串等);当</p>
</blockquote>
<p>想要创建自己的序列类型的时候,需要遵守某些协议。比如:不可变容器必须要定义__ len __方法和</p>
<p>__ getitem __方法;可变容器的协议除了上面提到的两个方法之外,还需要定义 setitem方法和delitem</p>
<p>方法;如果希望元素是可迭代的你需要定义__ iter __,这个方法返回一个迭代器。迭代器必须遵守迭</p>
<p>代器协议,需要定义__ iter __和next方法。容器背后的魔法方法如下:</p>
<ul>
<li>__ len __(self): 返回容器的长度,可变和不可变类型都需要实现</li>
<li>__ getitem __(self,key):定义对容器中某一项使用self[key]的方式进行读取操作时的行为,可变和不可变</li>
</ul>
<blockquote>
<p>容器类型都需要实现这个方法。在没有键的类型时产生TypeError异常,没有和键值相匹配时会产生</p>
<p>KeyError异常</p>
</blockquote>
<ul>
<li>__ setitem __(self,key):self[key]赋值操作时的行为,可变和不可变容器类型均需要实现,同时在合适的</li>
</ul>
<blockquote>
<p>时候产生KeyError和TypeError异常</p>
</blockquote>
<ul>
<li>__ iter __(self,key):返回当前容器的迭代器。迭代器以一连串的内容返回,最常用的就是iter()函数调用,</li>
</ul>
<blockquote>
<p>以及在类似 for i in container:的循环中被调用。迭代器是他们自己的对象,需要定义__ iter __方法</p>
</blockquote>
<ul>
<li><p>__ contains__(self,item): 定义使用in 和 not in 进行成员测试时类的行为</p></li>
<li><p>__ reversed __(self): 定义了对容器使用 reversed()内建函数的行为,它应该返回一个反转之后的序列</p></li>
<li><p>__ missing __ (self,key): 定义了当视图访问一个字典中不存在的键时的行为</p></li>
</ul>
<blockquote>
<p>一个典型的示例:</p>
</blockquote>
<pre><code class="language-python">class FunctionalList:
#这是一个列表的封装类,实现了一些额外的函数式:head、tail、init、last、drop和take
def __init__(self,values = None):
if values is None:
self.values = []
else:
self.values = values
def __len__(self):
return len(self,key)
def __getitem__(self,key):
#如果键的类型或值不合法,列表会返回异常
return self.values[key]
def __delitem__(self,key):
del self.values[key]
def __iter__(self):
return iter(self.values)
def __reversed__(self):
return reversed(self.values)
def append(self,value):
self.values.append(value)
def head(self):
return self.values[0]
def tail(self):
return self.values[1:] #取得除第一个元素外的所有元素
def init(self):
return self.values[:-1] #取得除最后一个元素外的所有元素
def last(self):
#取得最后一个元素
return self.values[-1]
def drop(self,n):
#取得除前n个元素外的所有元素
return self.values[n:]
def take(self,n):
return self.values[:n]
</code></pre>
<p>6.反射</p>
<ul>
<li><p>__ instancecheck __ (self,check): 检查一个实例是否是你定义的类的一个实例</p></li>
<li><p>__ subclasscheck__(self,subclass):检查一个类是否是你定义类的子类</p></li>
</ul>
<p>7.可调用对象</p>
<blockquote>
<p>在Python中,函数也是一种对象,也就意味着它们可以像其他任何对象一样被传递到函数或者方法中,</p>
</blockquote>
<ul>
<li>__ call __(self,[args....]): 允许一个类的实例像函数那样被调用,一般用于需要经常改变状态的类的实例</li>
</ul>
<p>8.拷贝</p>
<blockquote>
<p>当你想要改变一个对象而且不影响原有的对象时,可以使用Python中的copy模块</p>
</blockquote>
<ul>
<li>__ copy __(self):定义对类的实例使用copy.copy()时的行为;copy.copy()返回一个对象的浅拷贝,即拷贝</li>
</ul>
<blockquote>
<p>出的实例是全新的,然而里面的数据全是引用的,浅拷贝中的数据更改会影响原对象</p>
</blockquote>
<ul>
<li>__ deepcopy __(self,memodict=): 定义对类的实例使用deepcopy()时的行为。deepcopy()会返回一个</li>
</ul>
<blockquote>
<p>对象的深拷贝,这个对象和它的数据全都被拷贝了一遍。memodict是一个先前拷贝对象的缓存,它优化</p>
<p>了拷贝的过程,可以防止拷贝递归数据结构时产生无限递归;如果你想要拷贝一个单独的属性时,在那个</p>
<p>属性上调用copy.deepcopy()函数,使用memodict作为第一个参数</p>
</blockquote>
<p>10.Pickling</p>
<blockquote>
<p>Pickling是Python数据结构的序列化过程,当你想要存储一个对象再取出读取时,Pickling会显得十分有用</p>
</blockquote>
<p>Pickle模块=不仅仅可以用于内建类型,任何遵守pickle协议的类都可以被pickle。Pickle协议有四个可选方法</p>
<ul>
<li>__ getnewargs__(self):通过这个方法改变类在反pickle时传递new函数的参数,返回一个参数元组</li>
<li>__ getstate __ (self): 可以自定义对象被pickle的状态,而不是使用对象的dict属性;这个状态在反pickle时</li>
</ul>
<blockquote>
<p>会被__ setstate__使用</p>
</blockquote>
<ul>
<li>__ setstate__ :和getstate方法相互依存;当这两个对象均被定义时,可以在pickle时使用任何方法保存对象</li>
</ul>
<blockquote>
<p>的任何状态</p>
<p>方法使用示例:</p>
</blockquote>
<pre><code class="language-python">class Slate:
#存储一个字符串和一个变更日志的类 每次被pickle都会忘记当前值
def __init__(self,value):
self.value = value
self.last_change = time.asctime()
self.history = {}
def change(self,new_value):
#改变当前值。将上一个值记录到历史
self.history[self.last_change] = self.value
self.value = new_value
self.last_change = time.asctime()
def __getstate__(self):
#不返回self.value或者self.last_change
#反pickle时得到一个空白的slate
return self.history
def __setstate__(self):
self.history = state
self.value,self.last_change = None,None
</code></pre>
</div>
<div class="post-footer">
</div>
</article>
<script src="https://utteranc.es/client.js"
repo="sin-coder/hugocomments"
issue-term="pathname"
theme="github-dark"
crossorigin="anonymous"
async>
</script>
</main>
</body>
</html>