早上看Python的开源项目时,想起__xxx__这些默认的方法有时太久不写Python就又忘记了,所以总结一下吧。
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
|
#-*- coding:utf-8 -*-
class Obj():
# 构造
def __init__(self):
print('__init__')
# 析构
def __del__(self):
print('__del__')
# 进入 with,需要返回self,因为返回就是with时获得的对象
def __enter__(self):
print('__enter__')
return self
# 退出 with
def __exit__(self ,type, value, traceback):
print('__exit__')
# return False
# repr(o)
def __repr__(self):
return '__repr__'
# print o
def __str__(self):
return '__str__'
# o[key]
def __getitem__(self,key):
print('__getitem__',key)
# 当访问不存在的属性时
# o.asdfdsf
def __getattr__(self, key):
print('__getattr__',key)
# 调用dir时,默认object中是看对象方法和属性的,必须返回一个list
# dir(o)
def __dir__(self):
print('__dir__')
return ['__dir__']
# 当循环对象时调用,for i in o
# 必须返回自身
def __iter__(self):
print('__iter__')
self.tick = 0
return self
# next的存在是因为python2用的是next,python3用的是__next__
def next(self):
return self.__next__()
# 和__iter__,配合,每次循环调用一次,直接调用raise StopIteration(),退出循环
def __next__(self):
self.tick += 1
if self.tick > 2:
raise StopIteration()
print('__next__', self.tick)
return '__next__'
# len(o),必须返回int
def __len__(self):
print ('__len__')
return 0
with Obj() as o:
print(o)
print(repr(o))
o[1]
o.asdfdsf
dir(o)
len(o)
for i in o:
pass
|
output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
__init__
__enter__
__str__
__repr__
__getitem__ 1
__getattr__ asdfdsf
__dir__
__len__
__iter__
__next__ 1
__next__ 2
__exit__
__del__
|