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?