Magic methods are always __
surrounded. For example __init__
, __len__
they are all common magic methods. Here are some magic methods that I have encountered.
setitem
对某个索引值赋值时
That is, assignment operations can be performed, such as
def __setitem__(self, k, v):
self.put(k, v)
In the case of the above code, the operation can be performed p['key'] = value
, that is, assign the key to k, the value to v, and execute the put(k, v) function. Therefore, __setitem__
the premise of establishment is that the operation in this function has the nature of assignment.
getitem
使用索引访问元素时
This operation takes value operations, such as
def __getitem__(self, key):
return self.get(key)
In the case of the above function, you can perform the z = p['key']
operation, that is, 'key'
pass it into the get(key) function to get the value.