Monday, November 18, 2024
Google search engine
HomeLanguages__getslice__ in Python

__getslice__ in Python

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.

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

[]

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments