当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。