网络编程
位置:首页>> 网络编程>> Python编程>> Python扩展内置类型详解

Python扩展内置类型详解

作者:KLeonard  发布时间:2023-03-19 17:23:36 

标签: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,但是继承了定制后的字符串表达方式来显示其变量名。

来源:https://blog.csdn.net/gavin_john/article/details/50733641

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com