📜  __getslice__ 在Python中

📅  最后修改于: 2022-05-13 01:54:19.447000             🧑  作者: Mango

__getslice__ 在Python中

在Python中,Dunder 方法是那些在方法名称中有两个前缀和后缀下划线的方法。它们也被称为魔法方法Dunder的意思是“双下划线”。它们通常用于运算符重载。这些方法不是由用户直接调用的,而是在类内部调用或调用的。 Dunder 方法的一些示例是__init__, __repr__, __getslice__, __getitem__

__getslice__()

__getslice__(self, 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)

输出

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

输出

[]