In Python, a container is customizable, such as a sequence type (such as a list, Ganso, string), or a mapping type (such as a dictionary) that belongs to a container type. To successfully implement container customization, we need to talk about protocols first. What is the agreement? Protocol (protocols) is similar to an interface in other programming languages, and it specifies which of your methods must be defined. However, the protocol in Python appears less formal. In fact, in Python, the protocol is more like a guide. Custom containers, then we have to know some of the protocols related to custom containers: A detailed description of the Python magic method.
1. If you wish to customize a container that is immutable, you only need to define the __len__ () and __getitem__ () methods.
2. In addition to the __len__ () and __getitem__ () methods, you will need to define the __setitem__ () and __delitem__ () two methods if you wish to customize the container to be variable.
classcountlist:def __init__(Self, *args): Self.values= [x forXinchargs]Print(self.values) Self.count={}.fromkeys (len (self.values), 0) # Initializes a dictionary with a key value of 0 to the number of parameters passed minus 1, and the value of each key defaults to 0, meaning that the elements in each custom container object are not accessed by defaultdef __len__(self):returnLen (self.values)def __getitem__(self, Key): Self.count[key]+ = 1 # The elements in a custom object are recorded once every time they are accessedreturnSelf.values[key]>>> C1 = countlist (1,3,5,7,9)[1, 3, 5, 7, 9]>>> C2 = countlist (2,4,6,8,10)[2, 4, 6, 8, 10]>>>c1.count{0:0,1:0, 2:0, 3:0, 4: 0}>>>Len (c1.count)5>>> c1[1]3>>> c2[1]4>>> c1[1]+c2[1]7>>>c1.count{0:0,1:2, 2:0, 3:0, 4: 0}>>>c2.count{0:0,1:2, 2:0, 3:0, 4: 0}>>>
Python custom Container