欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python擴(kuò)展內(nèi)置類型詳解

 更新時(shí)間:2018年03月26日 08:33:34   作者:KLeonard  
這篇文章主要為大家詳細(xì)介紹了Python擴(kuò)展內(nèi)置類型的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

除了實(shí)現(xiàn)新的種類的對(duì)象以外,類有時(shí)有用于擴(kuò)展Python的內(nèi)置類型的功能。主要有以下兩種技術(shù):

通過(guò)嵌入擴(kuò)展類型

下例把一些集合函數(shù)變成方法,而且新增了一些基本運(yùn)算符重載,實(shí)現(xiàn)了新的集合對(duì)象。對(duì)于多數(shù)類而言,這個(gè)類只是包裝了Python列表,以及附加的集合運(yùn)算。

#File setwrapper.py 
 
class Set: 
  def __init__(self,value=[]):#構(gòu)造函數(shù) 
    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) #返回一個(gè)新的Set 
 
  def union(self,other):#求并集 
    res = self.data[:] #復(fù)制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__': #測(cè)試用例 
  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]) 

重載索引運(yùn)算讓Set類的實(shí)例可以充當(dāng)真正的列表。運(yùn)行結(jié)果如下:

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

[5, 7] 

通過(guò)子類擴(kuò)展類型

從Python2.2開始,所有內(nèi)置類型都可以直接創(chuàng)建子類。
這樣讓你可以通過(guò)用戶定義的class語(yǔ)句,定制或擴(kuò)展內(nèi)置類型的行為:建立類型名稱的子類并對(duì)其進(jìn)行定制。類型的子類實(shí)例,可以用在原始的內(nèi)置類型能夠出現(xiàn)的任何地方。
例如,假如你對(duì)Python列表偏移值以0開始計(jì)算而不是1開始一直很困擾,這時(shí)你就可以編寫自己的子類,定制列表的核心行為,如下:

# 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) 

在這個(gè)文件中,MyList子類擴(kuò)展了內(nèi)置list類型的__getitem__索引運(yùn)算方法,把索引1到N映射到實(shí)際的0到N-1。運(yùn)行結(jié)果如下:

>>>  
['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'] 

有關(guān)另一個(gè)類型子類的例子,可以參考bool類型的實(shí)現(xiàn),可以看到bool類是int的子類,有兩個(gè)實(shí)例(True和False),行為就像整數(shù)1和0,但是繼承了定制后的字符串表達(dá)方式來(lái)顯示其變量名。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論