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重试装饰器示例
Feb 11 Python
python执行子进程实现进程间通信的方法
Jun 02 Python
对PyQt5中树结构的实现方法详解
Jun 17 Python
Python如何实现转换URL详解
Jul 02 Python
tensorflow 实现自定义layer并添加到计算图中
Feb 04 Python
python读取多层嵌套文件夹中的文件实例
Feb 27 Python
基于python 等频分箱qcut问题的解决
Mar 03 Python
python 在sql语句中使用%s,%d,%f说明
Jun 06 Python
Python configparser模块操作代码实例
Jun 08 Python
Django用内置方法实现简单搜索功能的方法
Dec 18 Python
Python爬虫获取op.gg英雄联盟英雄对位胜率的源码
Jan 29 Python
python爬取豆瓣电影TOP250数据
May 23 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变量存储的详解
2013/06/13 PHP
体育彩票排列三组选三算法分享
2014/03/07 PHP
PHP设计模式之适配器模式原理与用法分析
2018/04/25 PHP
PHP-FPM的配置与优化讲解
2019/03/15 PHP
PHP数组与字符串互相转换实例
2020/05/05 PHP
JavaScript 获得选中文本内容的方法
2009/02/15 Javascript
javascript 写类方式之七
2009/07/05 Javascript
jQuery 表单验证扩展(三)
2010/10/20 Javascript
JQuery扩展插件Validate 3通过参数设置错误信息
2011/09/05 Javascript
面向对象的Javascript之三(封装和信息隐藏)
2012/01/27 Javascript
js 获取坐标 通过JS得到当前焦点(鼠标)的坐标属性
2013/01/04 Javascript
bootstrap实现弹窗和拖动效果
2016/01/03 Javascript
页面间固定参数,通过cookie传值的实现方法
2017/05/31 Javascript
Vue自定义指令详解
2017/07/28 Javascript
JavaScript常见JSON操作实例分析
2018/08/08 Javascript
了解javascript中let和var及const关键字的区别
2019/05/24 Javascript
js canvas实现5张图片合成一张图片
2019/07/15 Javascript
详解vue修改elementUI的分页组件视图没更新问题
2020/11/13 Javascript
angular *Ngif else用法详解
2020/12/15 Javascript
[43:35]TI4 循环赛第二日Liquid vs Fnatic
2014/07/11 DOTA
[46:23]完美世界DOTA2联赛PWL S2 FTD vs Magma 第一场 11.20
2020/11/23 DOTA
[01:28]国服启动器接入蒸汽平台操作流程视频
2021/03/11 DOTA
python实现得到一个给定类的虚函数
2014/09/28 Python
Python搭建APNS苹果推送通知推送服务的相关模块使用指南
2016/06/02 Python
pandas 数据结构之Series的使用方法
2019/06/21 Python
python中多个装饰器的调用顺序详解
2019/07/16 Python
python 实现将小图片放到另一个较大的白色或黑色背景图片中
2019/12/12 Python
python下对hsv颜色空间进行量化操作
2020/06/04 Python
使用Python封装excel操作指南
2021/01/29 Python
印度婴儿用品在线商店:Firstcry.com
2016/12/05 全球购物
Gloeilampgoedkoop荷兰:在线购买灯泡
2019/02/16 全球购物
祖国在我心中演讲稿300字
2014/05/04 职场文书
大学生党员自我批评思想汇报
2014/10/10 职场文书
肖申克救赎观后感
2015/06/02 职场文书
心得体会该怎么写呢?
2019/06/27 职场文书
Python字符串格式化方式
2022/04/07 Python