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 相关文章推荐
Python实现的简单发送邮件脚本分享
Nov 07 Python
Python多进程multiprocessing用法实例分析
Aug 18 Python
Python算法之求n个节点不同二叉树个数
Oct 27 Python
python3获取当前文件的上一级目录实例
Apr 26 Python
Python获取昨天、今天、明天开始、结束时间戳的方法
Jun 01 Python
python使用tornado实现简单爬虫
Jul 28 Python
python中的协程深入理解
Jun 10 Python
python进程的状态、创建及使用方法详解
Dec 06 Python
python 读取更新中的log 或其它文本方式
Dec 24 Python
python自动识别文本编码格式代码
Dec 26 Python
Python实现图片识别加翻译功能
Dec 26 Python
python opencv通过按键采集图片源码
May 20 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中处理模拟rewrite 效果
2006/12/09 PHP
PHP学习笔记 IIS7下安装配置php环境
2012/10/29 PHP
ThinkPHP模板范围判断输出In标签与Range标签用法详解
2014/06/30 PHP
PHP统一页面编码避免乱码问题
2015/04/09 PHP
php获得客户端浏览器名称及版本的方法(基于ECShop函数)
2015/12/23 PHP
Laravel框架路由设置与使用示例
2018/06/12 PHP
javascript 鼠标滚轮事件
2009/04/09 Javascript
javascript Firefox与IE 替换节点的方法
2010/02/24 Javascript
js实现兼容IE6与IE7的DIV高度
2010/05/13 Javascript
使用JS进行目录上传(相当于批量上传)
2010/12/05 Javascript
js设置文本框中焦点位置在最后的示例代码(简单实用)
2014/03/04 Javascript
js的延迟执行问题分析
2014/06/23 Javascript
js实现键盘控制DIV移动的方法
2015/01/10 Javascript
基于javascript实现动态显示当前系统时间
2016/01/28 Javascript
深入理解bootstrap框架之入门准备
2016/10/09 Javascript
jQuery Easy UI中根据第一个下拉框选中的值设置第二个下拉框是否可以编辑
2016/11/29 Javascript
利用js实现前后台传送Json的示例代码
2018/03/29 Javascript
Vue.extend实现挂载到实例上的方法
2019/05/01 Javascript
Layui弹出层 加载 做编辑页面的方法
2019/09/16 Javascript
ElementUI Tree 树形控件的使用并给节点添加图标
2020/02/27 Javascript
python搭建微信公众平台
2016/02/09 Python
Python一个简单的通信程序(客户端 服务器)
2019/03/06 Python
Python 画出来六维图
2019/07/26 Python
python修改字典键(key)的方法
2019/08/05 Python
详解tensorflow之过拟合问题实战
2020/11/01 Python
利用python实现后端写网页(flask框架)
2021/02/28 Python
详解FireFox下Canvas使用图像合成绘制SVG的Bug
2019/07/10 HTML / CSS
英国领先的高街书籍专家:Waterstones
2018/02/01 全球购物
iHerb中文官网:维生素、保健品和健康产品
2018/11/01 全球购物
Hoover胡佛官网:美国吸尘器和洗地机品牌
2019/01/09 全球购物
Cynthia Rowley官网:全球领先的生活方式品牌
2020/10/27 全球购物
单位介绍信范文
2014/01/18 职场文书
驾驶员岗位职责
2014/01/29 职场文书
CSS3 天气图标动画效果
2021/04/06 HTML / CSS
JVM的类加载器和双亲委派模式你了解吗
2022/03/13 Java/Android
python装饰器代码解析
2022/03/23 Python