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自动化测试实例解析
Sep 28 Python
Python语法快速入门指南
Oct 12 Python
Python如何实现文本转语音
Aug 08 Python
Python datetime和unix时间戳之间相互转换的讲解
Apr 01 Python
Flask框架学习笔记之表单基础介绍与表单提交方式
Aug 12 Python
Python面向对象编程基础实例分析
Jan 17 Python
Python读写操作csv和excle文件代码实例
Mar 16 Python
python 比较字典value的最大值的几种方法
Apr 17 Python
pycharm 激活码及使用方式的详细教程
May 12 Python
Python 调用 ES、Solr、Phoenix的示例代码
Nov 23 Python
在PyCharm中安装PaddlePaddle的方法
Feb 05 Python
python使用BeautifulSoup 解析HTML
Apr 24 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
java微信开发之上传下载多媒体文件
2016/06/24 PHP
用JS剩余字数计算的代码
2008/07/03 Javascript
JavaScript中出现乱码的处理心得
2009/12/24 Javascript
让ie运行js时提示允许阻止内容运行的解决方法
2010/10/24 Javascript
简单漂亮的js弹窗可自由拖拽且兼容大部分浏览器
2013/10/22 Javascript
js实现文本框只允许输入数字并限制数字大小的方法
2015/08/19 Javascript
微信小程序 Audio API详解及实例代码
2016/09/30 Javascript
NodeJS遍历文件生产文件列表功能示例
2017/01/22 NodeJs
Vue分页组件实例代码
2017/04/17 Javascript
Vue 2.0中生命周期与钩子函数的一些理解
2017/05/09 Javascript
基于JavaScript实现五子棋游戏
2020/08/26 Javascript
vue中使用axios post上传头像/图片并实时显示到页面的方法
2018/09/27 Javascript
详解JSON和JSONP劫持以及解决方法
2019/03/08 Javascript
vue中@change兼容问题详解
2019/10/25 Javascript
Vue中错误图片的处理的实现代码
2019/11/07 Javascript
JS实现电脑虚拟键盘的操作
2020/06/24 Javascript
python实现将html表格转换成CSV文件的方法
2015/06/28 Python
Python实现批量修改文件名实例
2015/07/08 Python
Python队列的定义与使用方法示例
2017/06/24 Python
Python调用C# Com dll组件实战教程
2017/10/12 Python
一些Centos Python 生产环境的部署命令(推荐)
2018/05/07 Python
基于Python对数据shape的常见操作详解
2018/12/25 Python
django 做 migrate 时 表已存在的处理方法
2019/08/31 Python
Flask项目中实现短信验证码和邮箱验证码功能
2019/12/05 Python
Python +Selenium解决图片验证码登录或注册问题(推荐)
2020/02/09 Python
python 在右键菜单中加入复制目标文件的有效存放路径(单斜杠或者双反斜杠)
2020/04/08 Python
关于jupyter打开之后不能直接跳转到浏览器的解决方式
2020/04/13 Python
websocket+sockjs+stompjs详解及实例代码
2018/11/30 HTML / CSS
生产助理岗位职责
2014/06/18 职场文书
群教个人对照检查材料
2014/08/20 职场文书
出生医学证明书
2014/09/15 职场文书
党员民主生活会整改措施
2014/09/26 职场文书
高校群众路线教育实践活动剖析材料
2014/10/10 职场文书
环保证明
2015/06/23 职场文书
《揠苗助长》教学反思
2016/02/20 职场文书
MySql学习笔记之事务隔离级别详解
2021/05/12 MySQL