怎么在Python中通過自定義對(duì)象實(shí)現(xiàn)一個(gè)切片功能-創(chuàng)新互聯(lián)

怎么在Python中通過自定義對(duì)象實(shí)現(xiàn)一個(gè)切片功能?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

創(chuàng)新互聯(lián)公司從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元海西做網(wǎng)站,已為上家服務(wù),為海西各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:13518219792python可以做什么

Python是一種編程語(yǔ)言,內(nèi)置了許多有效的工具,Python幾乎無(wú)所不能,該語(yǔ)言通俗易懂、容易入門、功能強(qiáng)大,在許多領(lǐng)域中都有廣泛的應(yīng)用,例如最熱門的大數(shù)據(jù)分析,人工智能,Web開發(fā)等。

1、魔術(shù)方法:__getitem__()

想要使自定義對(duì)象支持切片語(yǔ)法并不難,只需要在定義類的時(shí)候給它實(shí)現(xiàn)魔術(shù)方法 __getitem__() 即可。所以,這里就先介紹一下這個(gè)方法。

語(yǔ)法: object.__getitem__(self, key)

官方文檔釋義:Called to implement evaluation of self[key]. For sequence types, the accepted keys should be integers and slice objects. Note that the special interpretation of negative indexes (if the class wishes to emulate a sequence type) is up to the __getitem__() method. If key is of an inappropriate type, TypeError may be raised; if of a value outside the set of indexes for the sequence (after any special interpretation of negative values), IndexError should be raised. For mapping types, if key is missing (not in the container), KeyError should be raised.

概括翻譯一下:__getitem__() 方法用于返回參數(shù) key 所對(duì)應(yīng)的值,這個(gè) key 可以是整型數(shù)值和切片對(duì)象,并且支持負(fù)數(shù)索引;如果 key 不是以上兩種類型,就會(huì)拋 TypeError;如果索引越界,會(huì)拋 IndexError ;如果定義的是映射類型,當(dāng) key 參數(shù)不是其對(duì)象的鍵值時(shí),則會(huì)拋 KeyError 。

2、自定義序列實(shí)現(xiàn)切片功能

接下來(lái),我們定義一個(gè)簡(jiǎn)單的 MyList ,并給它加上切片功能。(PS:僅作演示,不保證其它功能的完備性)。

class MyList():
 def __init__(self):
  self.data = []
 def append(self, item):
  self.data.append(item)
 def __getitem__(self, key):
  print("key is : " + str(key))
  return self.data[key]

l = MyList()
l.append("My")
l.append("name")
l.append("is")
l.append("Python貓")

print(l[3])
print(l[:2])
print(l['hi'])

### 輸出結(jié)果:
key is : 3
Python貓
key is : slice(None, 2, None)
['My', 'name']
key is : hi
Traceback (most recent call last):
...
TypeError: list indices must be integers or slices, not str

從輸出結(jié)果來(lái)看,自定義的 MyList 既支持按索引查找,也支持切片操作,這正是我們的目的。

特別需要說明的是,此例中的 __getitem__() 方法會(huì)根據(jù)不同的參數(shù)類型而實(shí)現(xiàn)不同的功能(取索引位值或切片值),也會(huì)妥當(dāng)?shù)靥幚懋惓?,所以并不需要我們?cè)偃懛爆嵉奶幚磉壿?。網(wǎng)上有不少學(xué)習(xí)資料完全是在誤人子弟,它們會(huì)教你區(qū)分參數(shù)的不同類型,然后寫一大段代碼來(lái)實(shí)現(xiàn)索引查找和切片語(yǔ)法,簡(jiǎn)直是畫蛇添足。下面的就是一個(gè)代表性的錯(cuò)誤示例:

###略去其它代碼####
def __getitem__(self, index):
 cls = type(self)
 if isinstance(index, slice): # 如果index是個(gè)切片類型,則構(gòu)造新實(shí)例
  return cls(self._components[index])
 elif isinstance(index, numbers.Integral): # 如果index是個(gè)數(shù),則直接返回
  return self._components[index]
 else:
  msg = "{cls.__name__} indices must be integers"
  raise TypeError(msg.format(cls=cls))

3、自定義字典實(shí)現(xiàn)切片功能

切片是序列類型的特性,所以在上例中,我們不需要寫切片的具體實(shí)現(xiàn)邏輯。但是,對(duì)于其它非序列類型的自定義對(duì)象,就得自己實(shí)現(xiàn)切片邏輯。以自定義字典為例(PS:僅作演示,不保證其它功能的完備性):

class MyDict():
 def __init__(self):
  self.data = {}
 def __len__(self):
  return len(self.data)
 def append(self, item):
  self.data[len(self)] = item
 def __getitem__(self, key):
  if isinstance(key, int):
   return self.data[key]
  if isinstance(key, slice):
   slicedkeys = list(self.data.keys())[key]
   return {k: self.data[k] for k in slicedkeys}
  else:
   raise TypeError

d = MyDict()
d.append("My")
d.append("name")
d.append("is")
d.append("Python貓")
print(d[2])
print(d[:2])
print(d[-4:-2])
print(d['hi'])

### 輸出結(jié)果:
is
{0: 'My', 1: 'name'}
{0: 'My', 1: 'name'}
Traceback (most recent call last):
...
TypeError

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。

標(biāo)題名稱:怎么在Python中通過自定義對(duì)象實(shí)現(xiàn)一個(gè)切片功能-創(chuàng)新互聯(lián)
轉(zhuǎn)載源于:http://muchs.cn/article6/heeog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供手機(jī)網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)、品牌網(wǎng)站建設(shè)、電子商務(wù)、自適應(yīng)網(wǎng)站、App設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

網(wǎng)站優(yōu)化排名