Python magic method notes

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325977715&siteId=291194637