Python magic method

A cup of respectful sun, a cup of moonlight

The so-called magic method is to define some “unusual” methods in the custom class, so that the package of the class is more complete and functional, and it is a python-specific method. Their method names are generally in the format __xx__, such as the most common __init__, which is a magic method. Below I introduce some of the magic methods commonly found in the definition class, and attach the test code, please experience its wonderful magic charm.

Magic method

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
#! -*- coding:utf-8 -*-
class ClassTest(object):
def __new__(cls,*args,**kwargs):
''' Initialization operation, the first method to be called when the class is instantiated
Constructor with __init__ method
'''
return object.__new__(cls)
def __init__(self, _list=["1","2","3","4","5"] , _dict={"a":1,"b":2}):
''' Initialization operation '''
self._list = _list
self._dict = _dict
def __del__(self):
''' Delete variable '''
del self._list
del self._dict
def __call__(self, item):
'''
Usage:
>>>>func=ClassTest()
>>>>print func("nmask")
>>>>nmask
'''
return item
def __len__(self):
''' returns the length of the object
Usage:
>>>>print len(ClassTest())
>>>>5
'''
return len(self._list)
def __getitem__(self, key):
''' Take the value of the object by subscript
Usage:
>>>print ClassTest()["a"]
>>>1
'''
if key not in self._dict:
return self.__missing__(key)
return self._dict[key]
def __missing__(self,key):
''' When the key is not called in the dict '''
return "%s is not in dict" % key
def __setitem__(self, key, value):
''' set the value of the object
Usage:
ClassTest()['a']='12345'
'''
self._dict[key] = value
def __delitem__(self, key):
''' Delete object '''
del self._dict[key]
def __getattr__(self, item):
'''call this class when accessing an object whose object does not exist
Usage:
>>>ClassTest().abc
'''
return "class is not exists %s method" % item
def __contains__(self, item):
''' not in or in to determine if the element is in it
Usage:
>>>if "1" in ClassTest()
>>>
'''
return item in self._list
def __iter__(self):
''' Create an iterator
Usage:
>>>for i in ClassTest():
>>> print i
'''
return iter(self._list)
def __reversed__(self):
''' Reverse list
Usage:
>>>for i in reversed(ClassTest()):
>>> print i
'''
return reversed(self._list)
def __str__(self):
''' is used to process the output of the print instance itself, the default is the object name and memory address
Usage:
>>>print ClassTest()
'''
return "This is a Test Class for Python Magic Method"
def __repr__(self):
''' Serialized object
Usage:
>>>repr(ClassTest())
'''
return repr(self._dict)
def run(self):
return self._dict
if __name__=="__main__":
if "1" in ClassTest():
Print "calls the class's __contains__ method: 1 is in _list"
Print "calls the class's __missing__ method:", ClassTest()["aaa"]
for i in reversed(ClassTest()):
Print "calls the __iter__ method of the class:", i
Print "calls the class's __getattr__ method:", ClassTest().abc
Print "calls the class's __repr__ method:", repr(ClassTest())
Print "calls the class's __str__ method:", ClassTest()
Print "calls the class's __len__ method:", len(ClassTest())
Print "calls the class's __setitem__ method: ClassTest()['a']='12345'"
ClassTest()["a"]="12345"
Print "calls the class's __getitem__ method:", ClassTest()["a"]
for i in ClassTest():
Print "calls the __iter__ method of the class:", i

operation result:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
The class's __contains__ method is called: 1 is in _list
The class's __missing__ method is called: aaa is not in dict
The class's __iter__ method is called: 5
The class's __iter__ method is called: 4
The class's __iter__ method is called: 3
The __iter__ method of the class is called: 2
The __iter__ method of the class is called: 1
The class's __getattr__ method is called: class is not exists abc method
The class's __repr__ method is called: {'a': 1, 'b': 2}
The __str__ method of the class is called: This is a Test Class for Python Magic Method
The __len__ method of the class is called: 5
Called the class's __setitem__ method: ClassTest()['a']='12345'
The class's __getitem__ method is called: 12345
The __iter__ method of the class is called: 1
The __iter__ method of the class is called: 2
The class's __iter__ method is called: 3
The class's __iter__ method is called: 4
The class's __iter__ method is called: 5

More magic methods, reference: http://python.jobbole.com/88367/

本文标题:Python magic method

文章作者:nmask

发布时间:2017年11月22日 - 17:11

最后更新:2019年08月16日 - 15:08

原始链接:https://thief.one/2017/11/22/1/en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: