Python Magic Method Notes

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.