Magic methods are always __
surrounded, such as __init__
, __len__
are common magic method, here mainly write some of the magic methods I encountered
SetItem
对某个索引值赋值时
That is, you can perform assignment operations, such as
def__setitem__(self, k, v): self.put(k, v)
In the case of the above code, you can perform the p[‘key‘] = value
operation, assign the key to K,value to V, and execute the put (k, v) function. Therefore, the premise of the __setitem__
establishment is that the operation within the function would have been assigned to the nature of the value.
GetItem
使用索引访问元素时
This operation takes a value operation, such as
def__getitem__(self, key): returnself.get(key)
In the case of the above function, you can perform an z = p[‘key‘]
operation that will be ‘key‘
passed into the Get (key) function and be evaluated.
contain
使用 in 操作测试关系时
You can use this function when you want your object to be able to use the in
action:
def__contains__(self, key): ifselfself.root): returnTrue else: returnFalse
With this function you can execute:if ‘Northfield‘ in my_zip_tree:
PS: The most important thing to understand the magic function is that the function name corresponds to the representation of an action method, such as __contain__ (). If nothing is written in this function, then nothing can be returned without a in
syntax error, and there is no practical meaning. The Magic function is more important than the code inside the function, and this code is equivalent to the execution of the function name corresponding operation mode.
Finally send a large picture:
- Reference: Python Magic Method Guide
Python Magic Method Notes