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生成指定尺寸缩略图的示例
May 07 Python
详解python Todo清单实战
Nov 01 Python
Python实现的线性回归算法示例【附csv文件下载】
Dec 29 Python
10款最好的Python开发编辑器
Jul 03 Python
python3.6 tkinter实现屏保小程序
Jul 30 Python
Python获取当前脚本文件夹(Script)的绝对路径方法代码
Aug 27 Python
python中class的定义及使用教程
Sep 18 Python
pyqt5 QScrollArea设置在自定义侧(任何位置)
Sep 25 Python
pygame库实现移动底座弹球小游戏
Apr 14 Python
PyTorch中的Variable变量详解
Jan 07 Python
2020年10款优秀的Python第三方库,看看有你中意的吗?
Jan 12 Python
Python insert() / append() 用法 Leetcode实战演示
Mar 31 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函数实现判断是否移动端访问
2015/03/03 PHP
浅谈Laravel中的三种中间件的作用
2019/10/13 PHP
js下用gb2312编码解码实现方法
2009/12/31 Javascript
javascript实现获取cookie过期时间的变通方法
2014/08/14 Javascript
深入分析js的冒泡事件
2014/12/05 Javascript
通过XMLHttpRequest和jQuery实现ajax的几种方式
2015/08/28 Javascript
javascript实现粘贴qq截图功能(clipboardData)
2016/05/29 Javascript
bootstrap折叠调用collapse()后data-parent不生效的快速解决办法
2017/02/23 Javascript
多个上传文件用js验证文件的格式和大小的方法(推荐)
2017/03/09 Javascript
layui固定下拉框的显示条数(有滚动条)的方法
2019/09/10 Javascript
VUE实现图片验证码功能
2020/11/18 Javascript
vue通过v-html指令渲染的富文本无法修改样式的解决方案
2020/05/20 Javascript
解决Echarts2竖直datazoom滑动后显示数据不全的问题
2020/07/20 Javascript
vue实现几秒后跳转新页面代码
2020/09/09 Javascript
vue3.0中友好使用antdv示例详解
2021/01/05 Vue.js
python中wx将图标显示在右下角的脚本代码
2013/03/08 Python
python利用不到一百行代码实现一个小siri
2017/03/02 Python
Python基于QRCode实现生成二维码的方法【下载,安装,调用等】
2017/07/11 Python
AI人工智能 Python实现人机对话
2017/11/13 Python
在Python中使用gRPC的方法示例
2018/08/08 Python
浅谈Python中的异常和JSON读写数据的实现
2020/02/27 Python
python 读取二进制 显示图片案例
2020/04/24 Python
Pandas替换及部分替换(replace)实现流程详解
2020/10/12 Python
python 获取谷歌浏览器保存的密码
2021/01/06 Python
关联、聚合(Aggregation)以及组合(Composition)的区别
2012/02/29 面试题
中学生学习生活的自我评价
2013/10/26 职场文书
大学教师年终总结的自我评价
2013/10/29 职场文书
运动会表扬稿大全
2014/01/16 职场文书
优秀共产党员先进事迹
2014/01/27 职场文书
简历上的自我评价
2014/02/03 职场文书
《浅水洼里的小鱼》听课反思
2014/02/28 职场文书
幼儿园师德师风学习材料
2014/05/29 职场文书
2015年公共机构节能宣传周活动总结
2015/03/26 职场文书
小学开学典礼新闻稿
2015/07/17 职场文书
环境卫生整治简报
2015/07/20 职场文书
2016年学习雷锋精神广播稿
2015/12/17 职场文书