這篇文章主要介紹了Python實現擴展內置類型的方法,結合實例形式分析了Python嵌入內置類型擴展及子類方式擴展的具體實現技巧,需要的朋友可以參考下
本文實例講述了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擴展內建類型的實作方法分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!