Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

__getslice__ in Python

  • Last Updated : 10 May, 2020

In python, Dunder Methods are those methods which have two prefixes and suffix underscores in the method name. They are also called Magic methods. Dunder means “Double Underscores“. They are commonly used for operator overloading. These methods are not invoked directly by the user, but they are called or invoked internally from the class. Some examples of Dunder methods are __init__, __repr__, __getslice__, __getitem__ .

__getslice__()

__getslice__(self, i, j) is called when slice operator i.e. self[i:j] is invoked on an object. The returned object should be of the same type as self. It can be used on both mutable as well as immutable sequences.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Note: __getslice__ is deprecated since Python 2.0 and in Python 3.x it is not available. In place of this, we use __getitem__ method in python 3.x



Example 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']

Example 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

[]



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!