Python实现扩展内置类型的方法分析


Posted in Python onOctober 16, 2017

本文实例讲述了Python实现扩展内置类型的方法。分享给大家供大家参考,具体如下:

简介

除了实现新的类型的对象方式外,有时我们也可以通过扩展Python内置类型,从而支持其它类型的数据结构,比如为列表增加队列的插入和删除的方法。本文针对此问题,结合实现集合功能的实例,介绍了扩展Python内置类型的两种方法:通过嵌入内置类型来扩展类型和通过子类方式扩展类型。

通过嵌入内置类型扩展

下面例子通过将list对象作为嵌入类型,实现集合对象,并增加了一下运算符重载。这个类知识包装了Python的列表,以及附加的集合运算。

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]

通过子类方式扩展类型

从Python2.2开始,所有内置类型都能直接创建子类,如list,str,dict以及tuple。这样可以让你通过用户定义的class语句,定制或扩展内置类型:建立类型名称的子类并对其进行定制。类型的子类型实例,可用在原始的内置类型能够出现的任何地方。

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)

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
Ubuntu 14.04+Django 1.7.1+Nginx+uwsgi部署教程
Nov 18 Python
利用python批量给云主机配置安全组的方法教程
Jun 21 Python
在Python 中同一个类两个函数间变量的调用方法
Jan 31 Python
Pandas读写CSV文件的方法示例
Mar 27 Python
flask框架路由常用定义方式总结
Jul 23 Python
python通过txt文件批量安装依赖包的实现步骤
Aug 13 Python
Kears+Opencv实现简单人脸识别
Aug 28 Python
简单了解python协程的相关知识
Aug 31 Python
opencv3/python 鼠标响应操作详解
Dec 11 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
Jan 18 Python
Keras 快速解决OOM超内存的问题
Jun 11 Python
python 5个顶级异步框架推荐
Sep 09 Python
Python使用文件锁实现进程间同步功能【基于fcntl模块】
Oct 16 #Python
python利用paramiko连接远程服务器执行命令的方法
Oct 16 #Python
基于使用paramiko执行远程linux主机命令(详解)
Oct 16 #Python
python中文件变化监控示例(watchdog)
Oct 16 #Python
python中import reload __import__的区别详解
Oct 16 #Python
使用Python操作excel文件的实例代码
Oct 15 #Python
python出现"IndentationError: unexpected indent"错误解决办法
Oct 15 #Python
You might like
PHP.vs.JAVA
2016/04/29 PHP
Zend Framework入门教程之Zend_Db数据库操作详解
2016/12/08 PHP
PHP实现微信红包金额拆分试玩的算法示例
2018/04/07 PHP
laravel通过a标签从视图向控制器实现传值
2019/10/15 PHP
jquery实现奇偶行赋值不同css值
2012/02/17 Javascript
通过Javascript将数据导出到外部Excel文档的函数代码
2012/06/15 Javascript
JS判断移动端访问设备并加载对应CSS样式
2014/06/13 Javascript
JQuery操作元素的css样式
2015/03/09 Javascript
jQuery实现的背景动态变化导航菜单效果
2015/08/24 Javascript
node.js学习之交互式解释器REPL详解
2016/12/08 Javascript
nodejs操作mongodb的增删改查功能实例
2017/11/09 NodeJs
使用Vue完成一个简单的todolist的方法
2017/12/01 Javascript
详解js的作用域、预解析机制
2018/02/05 Javascript
vue.js给动态绑定的radio列表做批量编辑的方法
2018/02/28 Javascript
javascript中的this作用域详解
2019/07/15 Javascript
Node使用Selenium进行前端自动化操作的代码实现
2019/10/10 Javascript
[05:43]VG.R战队教练Mikasa专访:为目标从未停止战斗
2016/08/02 DOTA
剖析Python的Tornado框架中session支持的实现代码
2015/08/21 Python
Python使用正则表达式获取网页中所需要的信息
2018/01/29 Python
Python-OpenCV基本操作方法详解
2018/04/02 Python
python中的turtle库函数简单使用教程
2018/07/23 Python
Python使用logging模块实现打印log到指定文件的方法
2018/09/05 Python
python调试神器PySnooper的使用
2019/07/03 Python
基于python实现微信好友数据分析(简单)
2020/02/16 Python
没编程基础可以学python吗
2020/06/17 Python
python 使用三引号时容易犯的小错误
2020/10/21 Python
html5 canvas绘制放射性渐变色效果
2018/01/04 HTML / CSS
项目专员岗位职责
2013/12/04 职场文书
网上商城创业计划书范文
2014/01/31 职场文书
领导党性分析材料
2014/02/15 职场文书
欢迎领导标语
2014/06/27 职场文书
甜品店创业计划书
2014/08/14 职场文书
离婚起诉书范本
2015/05/18 职场文书
MyBatis配置文件解析与MyBatis实例演示
2022/04/07 Java/Android
windows安装 redis 6.2.6最新步骤详解
2022/04/26 Redis
nginx访问报403错误的几种情况详解
2022/07/23 Servers