當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python __getslice__用法及代碼示例


在python中,Dunder方法是那些在方法名稱中帶有兩個前綴和後綴下劃線的方法。它們也稱為魔術方法。 Dunder的意思是“雙下劃線”。它們通常用於操作員重載。這些方法不是由用戶直接調用的,而是從類內部調用或調用的。 Dunder方法的一些示例是__init__, __repr__, __getslice__, __getitem__

__getslice__()

__getslice __(自我,i,j)當切片運算符即self[i:j]在對象上調用。返回的對象應與self具有相同的類型。它可以用於可變序列和不可變序列。

注意: __getslice__從Python 2.0開始不推薦使用,在Python 3.x中不可用。取而代之的是,我們在python 3.x中使用__getitem__方法

範例1:

# program to demonstrate __getslice__ method 
  
class MyClass:
    def __init__(self, string):
        self.string = string 
          
    # method for creating list of words 
    def getwords(self):
        return self.string.split() 
          
    # method to perform slicing on the 
    # list of words 
    def __getslice__(self, i, j):
        return self.getwords()[max(0, i):max(0, j)] 
  
# Driver Code  
if __name__ == '__main__':  
  
    # object creation 
    obj = MyClass("Hello World ABC") 
      
    # __getslice__ method called internally 
    # from the class 
    sliced = obj[0:2] 
  
    # print the returned output 
    # return type is list 
    print(sliced)

OUTPUT



['Hello', 'World']

範例2:

# program to demonstrate __getslice__ method 
  
class MyClass:
    def __init__(self, string):
        self.string = string 
          
    # method for creating list of words 
    def getwords(self):
        return self.string.split() 
          
    # method to perform slicing on 
    # the list of words 
    def __getslice__(self, i, j):
        return self.getwords()[max(0, i):max(0, j)] 
  
# Driver Code  
if __name__ == '__main__':  
  
    # object creation 
    obj = MyClass("Hello World ABC") 
      
    # __getslice__ method called internally 
    # from the class 
    sliced = obj[0:0] 
  
    # print the returned output 
    # return type is list 
    print(sliced)

OUTPUT

[]





注:本文由純淨天空篩選整理自nishthagoel712大神的英文原創作品 __getslice__ in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。