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 16 Python
python动态加载变量示例分享
Feb 17 Python
Python解析json文件相关知识学习
Mar 01 Python
python安装numpy&安装matplotlib& scipy的教程
Nov 02 Python
python 图像平移和旋转的实例
Jan 10 Python
Pythony运维入门之Socket网络编程详解
Apr 15 Python
解决Django migrate不能发现app.models的表问题
Aug 31 Python
详解Python list和numpy array的存储和读取方法
Nov 06 Python
Python多线程模块Threading用法示例小结
Nov 09 Python
Python3+selenium实现cookie免密登录的示例代码
Mar 18 Python
python+requests接口压力测试500次,查看响应时间的实例
Apr 30 Python
python中24小时制转换为12小时制的方法
Jun 18 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
ajax实现无刷新分页(php)
2010/07/18 PHP
一些需要禁用的PHP危险函数(disable_functions)
2012/02/23 PHP
PHP面向对象精要总结
2014/11/07 PHP
PHP判断数据库中的记录是否存在的方法
2014/11/14 PHP
thinkPHP中volist标签用法示例
2016/12/06 PHP
PHP异常处理定义与使用方法分析
2017/07/25 PHP
PHP中通过getopt解析GNU C风格命令行选项
2019/11/18 PHP
gearman中任务的优先级和返回状态实例分析
2020/02/27 PHP
为你的 Laravel 验证器加上多验证场景的实现
2020/04/07 PHP
jquery 循环显示div的示例代码
2013/10/18 Javascript
鼠标经过tr时,改变tr当前背景颜色
2014/01/13 Javascript
node.js操作mongoDB数据库示例分享
2014/11/26 Javascript
javascript中Date对象应用之简易日历实现
2016/07/12 Javascript
浅析js的模块化编写 require.js
2016/12/07 Javascript
正则中的回溯定义与用法分析【JS与java实现】
2016/12/27 Javascript
jquery实现自适应banner焦点图
2017/02/16 Javascript
jquery 手势密码插件
2017/03/17 Javascript
js求数组中全部数字可拼接出的最大整数示例代码
2017/08/25 Javascript
Vue自定义指令结合阿里云OSS优化图片的实现方法
2019/11/12 Javascript
[58:59]完美世界DOTA2联赛PWL S3 access vs CPG 第一场 12.13
2020/12/16 DOTA
[01:16:13]DOTA2-DPC中国联赛 正赛 SAG vs Dragon BO3 第一场 2月22日
2021/03/11 DOTA
python遍历文件夹并删除特定格式文件的示例
2014/03/05 Python
通过mod_python配置运行在Apache上的Django框架
2015/07/22 Python
python设计模式大全
2016/06/27 Python
python调用API实现智能回复机器人
2018/04/10 Python
对Xpath 获取子标签下所有文本的方法详解
2019/01/02 Python
python psutil模块使用方法解析
2019/08/01 Python
在Python中使用filter去除列表中值为假及空字符串的例子
2019/11/18 Python
GDAL 矢量属性数据修改方式(python)
2020/03/10 Python
详解Python中openpyxl模块基本用法
2021/02/23 Python
html5自动播放mov格式视频的实例代码
2020/01/14 HTML / CSS
应届生会计电算化求职信
2013/10/03 职场文书
主题团日活动总结
2014/06/25 职场文书
晋江市人民政府党组群众路线教育实践活动整改方案
2014/10/25 职场文书
感谢信的技巧及范例
2019/05/15 职场文书
每日六道java新手入门面试题,通往自由的道路
2021/06/30 Java/Android