Python's magic methods are typically named in MethodName, such as: Init (construction method), GetItem, SetItem (subscriptable required method), Delitem (del Obj[key] Required method) , Len (Len (...) Required method) and so on.
In Python, if we want to implement a class similar to sequence and mapping, you can simulate it by rewriting the Magic method GetItem, SetItem, Delitem, Len.
The Magic method works:
GetItem (Self,key): Returns the value corresponding to the key.
SetItem (Self,key,value): Sets the value of the given key
Delitem (Self,key): Deletes the element corresponding to the given key.
Len (): Returns the number of elements
code example:
# coding:utf-8 ' desc: Try to define a new data type arithmetic progression author:pythontab.com ' class Arithemeticsequence (object): Def i NIT (self,start=0,step=1): print ' Call function init ' Self.start=start self.step=step Self.myda ta={} # defines how to get values def getitem (self,key): print ' Call function GetItem ' Try:return Self.myda Ta[key] except Keyerror:return Self.start+key*self.step # define Assignment Method Def setitem (Self,key,value): print ' Call function SetItem ' Self.mydata[key]=value # defines how to get length def len (self): print ' Call Functio n Len ' # here in order to see Len's role, we deliberately add length 1 return len (self.mydata) + 1 # define the method of deleting elements def delitem (self, key) : print ' Call function Delitem ' del Self.mydata[key] s=arithemeticsequence print s[3] # This should be done SELF.S Tart+key*self.step, because there is no 3 this keys[3] = 100 # for assignment print s[3] # before the assignment, then the direct output of the assigned value 100print len (s) # We deliberately added 1, should return 2del s[3] # Delete Besides 3 this keyprint s[3] # here shouldExecute Self.start+key*self.step because 3 of this key was deleted.
Output Result:
Call function Initcall function Getitem7call function Setitemcall function Getitem100call function Len2call function delit Emcall function Getitem7
The principle of these magic methods is: when we subscript the property of the class item, we will first be intercepted by GetItem (), SetItem (), Delitem (), so that we can set the operation in the method, such as assignment, modify content, delete content and so on.
"Recommended"
1. Learn more about the special function __len__ (self) in Python
2. Required knowledge--python Len Example
3. Summarize the use instances of the Len () function in Python
4. Example tutorials for using Python-specific class methods