magic methods 6

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:

  1. Write an unchangeable user-defined list, the number of everyone element being visited should be recorded.
1
2
3
4
5
6
7
8
9
10
11
class CountList:
def __init__(self, *args):
self.values = [x for x in args] #列表推导式
self.count = {}.fromkeys(range(len(self.values)), 0) #利用下标,初始0

def __len__(self):
return len(self.values)

def __getitem__(self, key):
self.count[key] += 1
return self.values[key]

Result:

1
2
3
4
5
6
7
8
9
10
>>> c1 = CountList(1,3,5,7,9)
>>> c2 = CountList(2,4,6,8,10)
>>> c1[1]
3
>>> c2[1]
4
>>> c1[1]+c2[1]
7
>>> c1.count
{0: 0, 1: 2, 2: 0, 3: 0, 4: 0}

  • How to write an unchangeable list?