Python Forum
Native support for array-slicing syntax?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Native support for array-slicing syntax?
#1
Hello,

A newbie question on the 'how' of the array slicing syntax.

Given that,
  1. Python does not support NumPy style arrays natively;
  2. NumPy is a package that you must import;
  3. Imported packages cannot in general extend or modify the syntax of a language;

how is NumPy able to support the colon syntax for slicing?

For example,
Quote:>>> from numpy import *
>>> a = array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ])
>>> a[:, 1:3]
array([[2, 3],
[5, 6],
[8, 9]])
>>>

In other words, if I were to create a NumPy-like package from scratch, what feature of Python would I use to support the colon-based syntax for slicing?

Many thanks.

Regards,
/nxs
Reply
#2
I don't know exactly how Numpy does it. But you could do it for your own classes by overriding __getitem__(key) and __setitem__(key, value). Whatever is in the brackets gets passed to those methods as the key parameter. In the example you give, it's a tuple of two slices. But as far as I know, it could be anything. And you could do anything with it. You could have it be the string 'one to five' and write code that would interpret that as 1:5 and return the appropriate slice of whatever.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Slicing a 2 dimensional array Scott 2 1,656 Jan-12-2022, 07:18 AM
Last Post: paul18fr
  View and extend native python class PythonDev 2 1,656 Oct-24-2020, 08:59 PM
Last Post: Gribouillis
  How To Unload Windows Native Extension ( .pyd )? zicklag 3 4,051 Mar-18-2020, 09:52 AM
Last Post: lexielightmap
  Pythonista script with iPhone's native Clock app Sharkman157 0 2,602 Sep-27-2018, 05:23 PM
Last Post: Sharkman157
  How to play a song .wav or .mp3 with audioop native library IvanSilva 3 6,553 Mar-14-2018, 10:49 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020