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实现随机调用一个浏览器打开网页
Apr 21 Python
详解配置Django的Celery异步之路踩坑
Nov 25 Python
python用post访问restful服务接口的方法
Dec 07 Python
pyqt5 QProgressBar清空进度条的实例
Jun 21 Python
Python实现的企业粉丝抽奖功能示例
Jul 26 Python
pytorch ImageFolder的覆写实例
Feb 20 Python
Python查找不限层级Json数据中某个key或者value的路径方式
Feb 27 Python
Django获取model中的字段名和字段的verbose_name方式
May 19 Python
PyInstaller运行原理及常用操作详解
Jun 13 Python
Django数据模型中on_delete使用详解
Nov 30 Python
Window10上Tensorflow的安装(CPU和GPU版本)
Dec 15 Python
基于Python实现射击小游戏的制作
Apr 06 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入门学习知识点四 PHP正则表达式基本应用
2011/07/14 PHP
php适配器模式介绍
2012/08/14 PHP
PHP图片处理之使用imagecopyresampled函数裁剪图片例子
2014/11/19 PHP
Zend Framework教程之Zend_Db_Table用法详解
2016/03/21 PHP
PHP抓取淘宝商品的用户晒单评论+图片+搜索商品列表实例
2016/04/14 PHP
php判断手机浏览还是web浏览,并执行相应的动作简单实例
2016/07/28 PHP
jQuery chili图片远处放大插件
2009/11/30 Javascript
javascript 学习笔记(onchange等)
2010/11/14 Javascript
基于jquery的放大镜效果
2012/05/30 Javascript
使用javascript实现ListBox左右全选,单选,多选,全请
2013/11/07 Javascript
JS实现判断碰撞的方法
2015/02/11 Javascript
Node.js编写爬虫的基本思路及抓取百度图片的实例分享
2016/03/12 Javascript
Angular2表单自定义验证器的实现
2016/10/19 Javascript
详解JavaScript常量定义
2017/01/03 Javascript
jQuery实现select下拉框获取当前选中文本、值、索引
2017/05/08 jQuery
JavaScript调试之console.log调试的一个小技巧分享
2017/08/07 Javascript
jquery鼠标悬停导航下划线滑出效果
2017/09/29 jQuery
在vue中,v-for的索引index在html中的使用方法
2018/03/06 Javascript
Vue SPA单页应用首屏优化实践
2018/06/28 Javascript
Vue开发实现吸顶效果的示例代码
2018/08/21 Javascript
如何实现一个webpack模块解析器
2018/10/24 Javascript
微信小程序--获取用户地理位置名称(无须用户授权)的方法
2019/04/29 Javascript
微信小程序文字显示换行问题
2019/07/28 Javascript
javascript设计模式 ? 单例模式原理与应用实例分析
2020/04/09 Javascript
Javascript执行上下文顺序的深入讲解
2020/11/04 Javascript
python 实现删除文件或文件夹实例详解
2016/12/04 Python
如何编写python的daemon程序
2021/01/07 Python
新奇的小玩意:IWOOT
2016/07/21 全球购物
英国骑行、跑步、游泳、铁人三项运动装备专卖店:Wiggle
2016/08/23 全球购物
卡骆驰新加坡官网:Crocs新加坡
2018/06/12 全球购物
艺术专业大学生自我评价
2013/09/22 职场文书
中药专业大学生医药工作求职信
2013/10/25 职场文书
小学毕业感言500字
2014/02/28 职场文书
店铺转让协议书(2014版)
2014/09/23 职场文书
行政经理岗位职责
2015/04/15 职场文书
Python中使用tkFileDialog实现文件选择、保存和路径选择
2022/05/20 Python