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:
class MyClass:
def __init__( self , string):
self .string = string
def getwords( self ):
return self .string.split()
def __getslice__( self , i, j):
return self .getwords()[ max ( 0 , i): max ( 0 , j)]
if __name__ = = '__main__' :
obj = MyClass( "Hello World ABC" )
sliced = obj[ 0 : 2 ]
print (sliced)
|
OUTPUT
['Hello', 'World']
Example 2:
class MyClass:
def __init__( self , string):
self .string = string
def getwords( self ):
return self .string.split()
def __getslice__( self , i, j):
return self .getwords()[ max ( 0 , i): max ( 0 , j)]
if __name__ = = '__main__' :
obj = MyClass( "Hello World ABC" )
sliced = obj[ 0 : 0 ]
print (sliced)
|
OUTPUT
[]
Last Updated :
10 May, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...