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中__init__和__new__的区别详解
Jul 09 Python
Python简单遍历字典及删除元素的方法
Sep 18 Python
利用python的socket发送http(s)请求方法示例
May 07 Python
python取数作为临时极大值(极小值)的方法
Oct 15 Python
详解pyenv下使用python matplotlib模块的问题解决
Nov 29 Python
Python+OpenCV图片局部区域像素值处理改进版详解
Jan 23 Python
详解python数据结构和算法
Apr 18 Python
Python3 A*寻路算法实现方式
Dec 24 Python
django 模型字段设置默认值代码
Jul 15 Python
Python使用jpype模块调用jar包过程解析
Jul 29 Python
python3.9.1环境安装的方法(图文)
Feb 02 Python
Python  lambda匿名函数和三元运算符
Apr 19 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/10/23 PHP
Windows和Linux中php代码调试工具Xdebug的安装与配置详解
2014/05/08 PHP
PHP中soap的用法实例
2014/10/24 PHP
php通过array_push()函数添加多个变量到数组末尾的方法
2015/03/18 PHP
PHP实现HTTP断点续传的方法
2015/06/17 PHP
php实现基于pdo的事务处理方法示例
2017/07/21 PHP
PHP利用pdo_odbc实现连接数据库示例【基于ThinkPHP5.1搭建的项目】
2019/05/13 PHP
Laravel 模型使用软删除-左连接查询-表起别名示例
2019/10/24 PHP
Laravel实现批量更新多条数据
2020/04/06 PHP
PHP7生产环境队列Beanstalkd用法详解
2020/05/19 PHP
用javascript实现的支持lrc歌词的播放器
2007/05/17 Javascript
使用JavaScript获取地址栏参数的方法
2014/12/19 Javascript
jQuery中click事件的定义和用法
2014/12/20 Javascript
JavaScript中Cookie操作实例
2015/01/09 Javascript
JavaScript中常见的字符串操作函数及用法汇总
2015/05/04 Javascript
jQuery 获取遍历获取table中每一个tr中的第一个td的方法
2016/10/05 Javascript
详解nodeJS中读写文件方法的区别
2017/03/06 NodeJs
Three.js 再探 - 写一个微信跳一跳极简版游戏
2018/01/04 Javascript
在Vue methods中调用filters里的过滤器实例
2018/08/30 Javascript
JS使用对象的defineProperty进行变量监控操作示例
2019/02/02 Javascript
JavaScript箭头函数中的this详解
2019/06/19 Javascript
微信小程序12行js代码自己写个滑块功能(推荐)
2020/07/15 Javascript
用Python编程实现语音控制电脑
2014/04/01 Python
在Python中使用列表生成式的教程
2015/04/27 Python
python编写计算器功能
2019/10/25 Python
Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)
2019/12/04 Python
DVF官方网站:美国时装界尊尚品牌
2017/08/29 全球购物
西班牙美妆电商:Perfume’s Club(有中文站)
2018/08/08 全球购物
ECCO英国官网:丹麦鞋履品牌
2019/09/03 全球购物
澳大利亚二手奢侈品网站:Modsie
2019/09/23 全球购物
历史专业个人求职信分享
2013/12/20 职场文书
领班岗位职责范文
2014/02/06 职场文书
防邪知识进家庭活动方案
2014/08/26 职场文书
大学生心理健康活动总结
2015/05/08 职场文书
欢送会主持词
2015/07/01 职场文书
高三教师工作总结2015
2015/07/21 职场文书