dog[::,::,::] in Python And How This Is Possible

The closest thing you might have seen to this might be in pandas
# df is some pandas DataFrame
df.iloc[:, :3]^ selecting some rows and some columns using pandas
Default dog[::,::,::] behaviour
class Dog:
pass
dog = Dog()
print(dog[::,::,::]) # ERROR^ by default, we get an error
Defining __getitem__
class Dog:
def __getitem__(self, key):
return key
dog = Dog()
print(dog[1]) # 1
print(dog[2]) # 2
print(dog['apple']) # applewhen we define the __getitem__ magic method, we are actually defining our Dog object’s behaviour if we try to dog[key]
Here, we define __getitem__ to return key itself. Which means that if we do dog[1] we will simply get 1, and if we do dog['apple'] we will simply get 'apple'
dog[::]
class Dog:
def __getitem__(self, key):
return key
dog = Dog()
print(dog[1]) # 1
print(dog[2]) # 2
print(dog[::]) # slice(None, None, None)^ without changing any code in the Dog class, notice what happens when we try dog[::] — we get slice(None, None, None)
When we slice anything eg. list, string etc using lis[2:0:5], we are actually passing in a slice object ie. lis[slice(2,0,5)]. So when we do dog[::], we are actualy doing dog[slice(None,None,None)]
__getitem__ with multiple arguments
class Dog:
def __getitem__(self, key):
return key
dog = Dog()
print(dog[1]) # (1,)
print(dog[1,2]) # (1, 2)
print(dog[1,2,3,4,5]) # (1, 2,3 , 4, 5)By default, if we do dog[1, 2, 3], the tuple (1, 2, 3) is passed to the __getitem__ magic method.
dog[::, ::, ::]
dog[::, ::, ::]
is the same as:
dog[slice(None, None, None), slice(None, None, None), slice(None, None, None)]And so
class Dog:
def __getitem__(self, key):
return key
dog = Dog()
print(dog[::,::,::])
# (slice(None, None, None), slice(None, None, None), slice(None, None, None))Conclusion
Ignoring this dumb dog example, you can now customize your classes and objects to take in more complex slices
If You Wish To Support Me As A Creator
- Clap 50 times for this story
- Leave a comment telling me your thoughts
- Highlight your favourite part of the story
Thank you! These tiny actions go a long way, and I really appreciate it!
YouTube: https://www.youtube.com/@zlliu246
LinkedIn: https://www.linkedin.com/in/zlliu/






