Python implements extended built-in type method analysis, and python implements built-in types

Source: Internet
Author: User
Tags new set python list

Python implements extended built-in type method analysis, and python implements built-in types

This example describes how to implement extension built-in types in Python. We will share this with you for your reference. The details are as follows:

Introduction

In addition to implementing new types of objects, we can also extend the Python built-in types to support other types of data structures, such as adding queue insertion and deletion methods to the list. This document introduces two methods to extend the Python built-in type by embedding the built-in type and extending the type by subclass.

Embedded built-in Type Extension

In the following example, the list object is used as the embedded type to implement the set object and the following operator overload is added. This knowledge class encapsulates the Python list and additional set operations.

class Set:  def __init__(self, value=[]): # Constructor    self.data = [] # Manages a list    self.concat(value)  def intersect(self, other): # other is any sequence    res = [] # self is the subject    for x in self.data:      if x in other: # Pick common items        res.append(x)    return Set(res) # Return a new Set  def union(self, other): # other is any sequence    res = self.data[:] # Copy of my list    for x in other: # Add items in other      if not x in res:        res.append(x)    return Set(res)  def concat(self, value): # value: list, Set...    for x in value: # Removes duplicates      if not x in self.data:        self.data.append(x)  def __len__(self):     return len(self.data) # len(self)  def __getitem__(self, key): return self.data[key] # self[i]  def __and__(self, other):  return self.intersect(other) # self & other  def __or__(self, other):  return self.union(other) # self | other  def __repr__(self):     return 'Set:' + repr(self.data) # print()if __name__ == '__main__':  x = Set([1, 3, 5, 7])  print(x.union(Set([1, 4, 7]))) # prints Set:[1, 3, 5, 7, 4]  print(x | Set([1, 4, 6])) # prints Set:[1, 3, 5, 7, 4, 6]

Extend the type by subclass

From Python2.2, all built-in types can directly create subclasses, such as list, str, dict, and tuple. This allows you to customize or extend the built-in type through the user-defined class statement: Create and customize the subclass of the type name. A child-type instance can appear anywhere in the original built-in type.

class Set(list):  def __init__(self, value = []):   # Constructor    list.__init__([])        # Customizes list    self.concat(value)        # Copies mutable defaults  def intersect(self, other):     # other is any sequence    res = []             # self is the subject    for x in self:      if x in other:        # Pick common items        res.append(x)    return Set(res)         # Return a new Set  def union(self, other):       # other is any sequence    res = Set(self)         # Copy me and my list    res.concat(other)    return res  def concat(self, value):       # value: list, Set . . .    for x in value:         # Removes duplicates      if not x in self:        self.append(x)  def __and__(self, other): return self.intersect(other)  def __or__(self, other): return self.union(other)  def __repr__(self):    return 'Set:' + list.__repr__(self)if __name__ == '__main__':  x = Set([1,3,5,7])  y = Set([2,1,4,5,6])  print(x, y, len(x))  print(x.intersect(y), y.union(x))  print(x & y, x | y)  x.reverse(); print(x)

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.