The magic method of Python is generally named in the form of _ methodname _, for example, __init _ (constructor ), __getitem _, _ setitem _ (method required for subscriptable), the magic method of Python is generally named in the form of methodname, such as: init (constructor ), getitem, setitem (method required for subscriptable), delitem (method required for del obj [key]), len (...) Required method.
In Python, if we want to create classes similar to sequences and mappings, we can simulate them by rewriting the magic methods getitem, setitem, delitem, and len.
Role of magic methods:
Getitem (self, key): value corresponding to the return key.
Setitem (self, key, value): set the value of the given key
Delitem (self, key): deletes the elements corresponding to a given key.
Len (): number of returned elements
Code example:
# Coding: UTF-8 ''' desc: try to define a new data type equality series author: pythontab.com ''' class ArithemeticSequence (object): def init (self, start = 0, step = 1): print 'Call function init 'self. start = start self. step = step self. myData ={}# define the method for obtaining the value def getitem (self, key): print 'Call function getitem 'try: return self. myData [key] doesn t KeyError: return self. start + key * self. step # define the value assignment method def setitem (self, key, value): print 'Call function setitem 'self. myData [key] = value # define the method for obtaining the length def len (self): print 'Call function Len' # here to see the role of len, we intentionally increase the length by 1 return len (self. myData) + 1 # define the method def delitem (self, key) for deleting an element: print 'Call function delitem' del self. myData [key] s = ArithemeticSequence (1, 2) print s [3] # self should be executed here. start + key * self. step, because no 3 keys [3] = 100 # are assigned the print s [3] # prior to the assignment, then the assigned value 100 print len (s) is directly output) # If We intentionally add 1, we should return 2del s [3] # delete 3. this keyprint s [3] # Here we should execute self. start + key * self. step, because the key 3 is deleted
Output result:
Call function initCall function getitem7Call function setitemCall function getitem100Call function len2Call function delitemCall function getitem7
The principle of these magic methods is: when we perform the following operations on the attribute item of the class, it will first be intercepted by getitem (), setitem (), delitem, this allows you to set operations in methods, such as assigning values, modifying content, and deleting content.
The above are the details of the Python magic methods _ getitem _, _ setitem _, _ delitem _, and _ len, for more information, see other related articles in the first PHP community!