Python Class Special method __getitem__ how to use?

Source: Internet
Author: User

This article shares with you the main isPythonspecial methods for classes__GETITEM__ related content, take a look at it, I hope you learn Python help.which defines this in the class.__getitem__method, then its instance object (assumed to beP), can be like this P[key]value when the instance object doesP[key]operation, methods in the class are called__getitem__. Let's use an exaggerated example to illustrate the problem.
when an instance object passes[]the method that invokes the operator when it takes a value__getitem__, you can see the output of two smiley faces from the above code. This is generally used ’’’HuanggoPythoncontact information, search by yourself ’’’ classDataBase: "' Python 3the class in" " def__init__(Self, ID, address): ’’’Initialize Method" " Self.id = ID Self.address = Address SELF.D = {self.id:1, Self.address: "192.168.1.1", } def__getitem__(Self, key): # return Self.__dict__.get (Key, "100") returnSelf.d.get (Key, "default") data = DataBase (1, "192.168.2.11") Print (data["HI"]) Print (Data[data.id])or ’’’HuanggoPythoncontact information, search by yourself ’’’ classDataBase: "' Python 3the class in" " def__init__(Self, ID, address): ’’’Initialize Method" " Self.id = ID Self.address = Address def__getitem__(Self, key): returnSelf.__dict__.get (Key, "100") data = DataBase (1, "192.168.2.11") Print (data["HI"]) Print (data["id"]) Source: Network

Python Class Special method __getitem__ how to use?

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.