Python custom Container

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.