Special _ getitem _ and _ setitem _ methods of Python classes, pythonsetitem

Source: Internet
Author: User

Special _ getitem _ and _ setitem _ methods of Python classes, pythonsetitem

For example, you can use the PyScripter debugger to perform step-by-step tracking to view the details of the image structure.

The original object is changed. the ready-made _ setitem _ is used in _ getitem _ when the sub-object attribute is not defined.

# Encoding: UTF-8 "" This class inherits the object, which is the smallest unit of Python. You can use dir (objct) in the Python ">>>" Console) or dir (_ builtins __. object) command to view its properties, You can see _ setattr __, _ new __... they are attributes of any object in python. You can also look at dir (1) and dir (int) to see more. Here, 1 appears as an instantiated int object. What are the functions of these _ xxx _ attributes? In the following code, we can understand the usage of _ getitem _ and _ setitem _ (these two attributes are very important in dict objects) "class WPUnit (object): def _ init _ (self): self. _ res = {} def _ setitem _ (self, key, val): self. _ res [key] = valdef _ getitem _ (self, key): if self. _ res. has_key (key): return self. _ res [key] else: r = WPUnit () self. _ setitem _ (key, r) return ra = WPUnit () a ['a'] ['B'] ['C'] ['D'] ['E'] ['E'] ['F'] ['G'] = 5 print ['a'] ['B'] ['C'] ['D'] ['E'] ['E'] ['F'] ['G']
>>> class testsetandget:   kk = {};   def __getitem__(self, key):     return self.kk[key];   def __setitem__(self, key, value):     self.kk[key] = value;      >>> a = testsetandget() >>> a['first'] = 1 >>> a['first'] 1 >>> a.__setitem__('second', 2) >>> a.__getitem__('second') 2 >>> a['second'] 2 >>>  

The above is a simple introduction to the special _ getitem _ and _ setitem _ methods of the Python class. I hope you can provide more support for our guests ~

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.