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使用rabbitmq实现网络爬虫示例
Feb 20 Python
python中的实例方法、静态方法、类方法、类变量和实例变量浅析
Apr 26 Python
Python的Bottle框架中返回静态文件和JSON对象的方法
Apr 30 Python
python&MongoDB爬取图书馆借阅记录
Feb 05 Python
Python中工作日类库Busines Holiday的介绍与使用
Jul 06 Python
Python实现连接两个无规则列表后删除重复元素并升序排序的方法
Feb 05 Python
python selenium 获取标签的属性值、内容、状态方法
Jun 22 Python
解决pyecharts在jupyter notebook中使用报错问题
Apr 23 Python
详解python播放音频的三种方法
Sep 23 Python
python 使用while写猜年龄小游戏过程解析
Oct 07 Python
python Django 反向访问器的外键冲突解决
May 20 Python
python和go语言的区别是什么
Jul 20 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
利用递归把多维数组转为一维数组的函数
2006/10/09 PHP
PHP小技巧搜集,每个PHPer都来露一手
2007/01/02 PHP
PHP 分页原理分析,大家可以看看
2009/12/21 PHP
PHP在引号前面添加反斜杠(PHP去除反斜杠)
2013/09/28 PHP
ThinkPHP页面跳转success与error方法概述
2014/06/25 PHP
php+ajax实现文章自动保存的方法
2014/12/30 PHP
PHP答题类应用接口实例
2015/02/09 PHP
php计算整个目录大小的方法
2015/06/01 PHP
PHP获取表单数据与HTML嵌入PHP脚本的实现
2017/02/09 PHP
深入理解Yii2.0乐观锁与悲观锁的原理与使用
2017/07/26 PHP
phpStudy配置多站点多域名和多端口的方法
2017/09/01 PHP
PHP+JS实现的实时搜索提示功能
2018/03/13 PHP
PHP的Trait机制原理与用法分析
2019/10/18 PHP
php ActiveMQ的安装与使用方法图文教程
2020/02/23 PHP
jQuery中Ajax的load方法详解
2015/01/14 Javascript
javascript实现按回车键切换焦点
2015/02/09 Javascript
BootStrap中Tab页签切换实例代码
2016/05/30 Javascript
Bootstrap CSS组件之下拉菜单(dropdown)
2016/12/17 Javascript
微信小程序 MD5加密登录密码详解及实例代码
2017/01/12 Javascript
JS点击缩略图整屏居中放大图片效果
2017/07/04 Javascript
python远程登录代码
2008/04/29 Python
详解Python进程间通信之命名管道
2017/08/28 Python
浅谈python3中input输入的使用
2019/08/02 Python
Django用户认证系统 Web请求中的认证解析
2019/08/02 Python
python爬虫豆瓣网的模拟登录实现
2019/08/21 Python
python求前n个阶乘的和实例
2020/04/02 Python
Woolworth官网:澳洲第一大超市
2017/06/25 全球购物
美国正版电视节目和电影在线观看:Hulu
2018/05/24 全球购物
Servlet如何得到客户端机器的信息
2014/10/17 面试题
挑战杯创业计划书的写作指南
2014/01/07 职场文书
社团招新策划书
2014/02/04 职场文书
部队万能检讨书
2014/02/20 职场文书
葬礼司仪主持词
2014/03/31 职场文书
初中优秀教师事迹材料
2014/08/18 职场文书
公证处委托书
2015/01/28 职场文书
欠条范文
2015/07/03 职场文书