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 ~