Magic Methods 6
Magic Methods : customize the container
Protocols : it is similar with the port in other program language. In Python, it functions as a guide.
Container : Alignment[list, tuple, string] and mapping[dictionary].
The container you customize is sorted as two kinds. One is the unchangeable container, in which you only need to define the __len__() and __getitem__(). The other is the changeable one, in which you should define the __setitem__() and __delitem__() based on the former container.
| Magic Methods | Meaning |
|---|---|
| __len__(self) | define the behavior when ‘len’ is called (returned value: number of elements) |
| __getitem__(self, key) | define the behavior when getting the certain element (self[key]) |
| __setitem__(self, key, value) | define the behavior when setting the certain element (self[key]=value) |
| __delitem__(self, key) | define the behavior when deleting the certain element (del self[key]) |
| __iter__(self) | define the behavior of certain element when iteration |
| __reversed__(self) | define the behavior when reversed() is called. |
| __contains__(self, item) | define the behavior when use the in or not in |
Trial:
- Write an unchangeable user-defined list, the number of everyone element being visited should be recorded.
1 | |
Result:
1 | |
- How to write an unchangeable list?
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!