脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python扩展内置类型详解

Python扩展内置类型详解

2021-01-24 01:08KLeonard Python

这篇文章主要为大家详细介绍了Python扩展内置类型的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

通过嵌入扩展类型

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#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开始一直很困扰,这时你就可以编写自己的子类,定制列表的核心行为,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 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

延伸 · 阅读

精彩推荐