Python扩展内置类型详解

yipeiwu_com6年前Python基础

除了实现新的种类的对象以外,类有时有用于扩展Python的内置类型的功能。主要有以下两种技术:

通过嵌入扩展类型

下例把一些集合函数变成方法,而且新增了一些基本运算符重载,实现了新的集合对象。对于多数类而言,这个类只是包装了Python列表,以及附加的集合运算。

#File setwrapper.py 
 
class Set: 
  def __init__(self,value=[]):#构造函数 
    self.data = [] 
    self.concat(value) 
  def intersect(self,other):#求交集 
    res = [] 
    for x in self.data: 
      if x in other: 
        res.append(x) 
    return Set(res) #返回一个新的Set 
 
  def union(self,other):#求并集 
    res = self.data[:] #复制self.data 
    for x in other: 
      if not x in res: 
        res.append(x) 
    return Set(res) 
 
  def concat(self,value): 
    for x in value: 
      if not x in self.data: 
        self.data.append(x) 
 
  def __len__(self): # len(self) 
    return len(self.data)  
 
  def __getitem__(self,key): # self[i] 
    return self.data[key] 
 
  def __and__(self,other): # self & other 
    return self.intersect(other)  
 
  def __or__(self,other): # self | other 
    return self.union(other) 
 
  def __repr__(self): # print 
    return 'Set:' + repr(self.data) 
 
if __name__ == '__main__': #测试用例 
  x = Set([1,3,5,7]) 
  print(x.union(Set([1,4,7]))) 
  print(x | Set([1,4,6])) 
  print(x[2]) 
  print(x[2:4]) 

重载索引运算让Set类的实例可以充当真正的列表。运行结果如下:

>>>  
Set:[1, 3, 5, 7, 4] 
Set:[1, 3, 5, 7, 4, 6] 

[5, 7] 

通过子类扩展类型

从Python2.2开始,所有内置类型都可以直接创建子类。
这样让你可以通过用户定义的class语句,定制或扩展内置类型的行为:建立类型名称的子类并对其进行定制。类型的子类实例,可以用在原始的内置类型能够出现的任何地方。
例如,假如你对Python列表偏移值以0开始计算而不是1开始一直很困扰,这时你就可以编写自己的子类,定制列表的核心行为,如下:

# File typesubclass.py 
#Map 1..N to 0..N-1; call back to built-in version 
 
class MyList(list): 
  def __getitem__(self,offset): 
    print('(indexing %s at %s)'%(self,offset)) 
    return list.__getitem__(self,offset-1) 
 
if __name__ == '__main__': 
  print(list('abc')) 
  x = MyList('abc') 
  print(x) 
 
  print(x[1]) 
  print(x[3]) 
  x.append('spam') 
  print(x) 
  x.reverse() 
  print(x) 

在这个文件中,MyList子类扩展了内置list类型的__getitem__索引运算方法,把索引1到N映射到实际的0到N-1。运行结果如下:

>>>  
['a', 'b', 'c'] 
['a', 'b', 'c'] 
(indexing ['a', 'b', 'c'] at 1) 

(indexing ['a', 'b', 'c'] at 3) 

['a', 'b', 'c', 'spam'] 
['spam', 'c', 'b', 'a'] 

有关另一个类型子类的例子,可以参考bool类型的实现,可以看到bool类是int的子类,有两个实例(True和False),行为就像整数1和0,但是继承了定制后的字符串表达方式来显示其变量名。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

pandas DataFrame创建方法的方式

pandas DataFrame创建方法的方式

在pandas里,DataFrame是最经常用的数据结构,这里总结生成和添加数据的方法: ①、把其他格式的数据整理到DataFrame中; ②在已有的DataFrame中插入N列或者N...

详解Python数据分析--Pandas知识点

详解Python数据分析--Pandas知识点

本文主要是总结学习pandas过程中用到的函数和方法, 在此记录, 防止遗忘 1. 重复值的处理 利用drop_duplicates()函数删除数据表中重复多余的记录, 比如删除重复多余...

PyTorch中Tensor的拼接与拆分的实现

拼接张量:torch.cat() 、torch.stack() torch.cat(inputs, dimension=0) → Tensor 在给定维度上对输入的张量序列 s...

python打印异常信息的两种实现方式

1. 直接打印错误 try: # your code except KeyboardInterrupt: print("quit") except Excepti...

python写一个md5解密器示例

python写一个md5解密器示例

前言: md5解密,百度了一下发现教程不是很多也不详细。 这个图都没一张。。。 0x01 windows环境,kali也可以啊 burpsuite requests模块 bs4模块 0...