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实现保证只能运行一个脚本实例
Jun 24 Python
Python编写电话薄实现增删改查功能
May 07 Python
利用Python操作消息队列RabbitMQ的方法教程
Jul 19 Python
详解Python自建logging模块
Jan 29 Python
python 拼接文件路径的方法
Oct 23 Python
python使用for循环计算0-100的整数的和方法
Feb 01 Python
django如何通过类视图使用装饰器
Jul 24 Python
Python实现时间序列可视化的方法
Aug 06 Python
CentOS7下安装python3.6.8的教程详解
Jan 03 Python
pycharm 2019 最新激活方式(pycharm破解、激活)
Sep 22 Python
Django如何在不停机的情况下创建索引
Aug 02 Python
Python+Matplotlib+LaTeX玩转数学公式
Feb 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
PHP 组件化编程技巧
2009/06/06 PHP
mysql 性能的检查和优化方法
2009/06/21 PHP
dedecms系统的广告设置代码 基础版本
2010/04/09 PHP
php中ltrim()、rtrim()与trim()删除字符空格实例
2014/11/25 PHP
PHP使用redis实现统计缓存mysql压力的方法
2015/11/14 PHP
关于js中window.location.href,location.href,parent.location.href,top.location.href的用法与区别
2010/10/18 Javascript
js获取事件源及触发该事件的对象
2013/10/24 Javascript
jQuery实现选中弹出窗口选择框内容后赋值给文本框的方法
2015/11/23 Javascript
使用堆实现Top K算法(JS实现)
2015/12/25 Javascript
JavaScipt中栈的实现方法
2016/02/17 Javascript
JS实现title标题栏文字不间断滚动显示效果
2016/09/07 Javascript
js判断一个字符串是以某个字符串开头的简单实例
2016/12/27 Javascript
微信小程序 开发经验整理
2017/02/15 Javascript
利用js查找数组中指定元素并返回该元素的所有索引示例
2017/03/29 Javascript
jQuery实现页码跳转式动态数据分页
2017/12/31 jQuery
javaScript中"=="和"==="的区别详解
2018/03/16 Javascript
[01:14]3.19DOTA2发布会 三代刀塔人第二代
2014/03/25 DOTA
python探索之BaseHTTPServer-实现Web服务器介绍
2017/10/28 Python
python数字图像处理之高级形态学处理
2018/04/27 Python
python 函数的缺省参数使用注意事项分析
2019/09/17 Python
python实现双色球随机选号
2020/01/01 Python
Python loguru日志库之高效输出控制台日志和日志记录
2020/03/07 Python
Python使用Pyqt5实现简易浏览器(最新版本测试过)
2020/04/27 Python
增大python字体的方法步骤
2020/07/05 Python
Python虚拟环境virtualenv创建及使用过程图解
2020/12/08 Python
在html页面中取得session中的值的方法
2020/08/11 HTML / CSS
2019年Java面试必问之经典试题
2012/09/12 面试题
如何在Shell脚本中使用函数
2015/09/06 面试题
儿科护理实习自我鉴定
2013/09/19 职场文书
《望洞庭》教学反思
2014/02/16 职场文书
2014年党的群众路线教育实践活动总结
2014/04/25 职场文书
初中生思想道德自我评价
2015/03/09 职场文书
2016年优秀共产党员先进事迹材料
2016/02/29 职场文书
毕业欢送晚会主持词
2019/06/25 职场文书
springboot集成flyway自动创表的详细配置
2021/06/26 Java/Android
vue打包时去掉所有的console.log
2022/04/10 Vue.js