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 |
class CountList: |
Result:
1 |
>>> c1 = CountList(1,3,5,7,9) |
- How to write an unchangeable list?
近期评论