I am trying to use
__getitem__(self, x, y):
on my Matrix class, but it seems to me it doesn\'t work (I still don\'t know very well to use p
Indeed, when you execute bla[x,y]
, you're calling type(bla).__getitem__(bla, (x, y))
-- Python automatically forms the tuple for you and passes it on to __getitem__
as the second argument (the first one being its self
). There's no good way[1] to express that __getitem__
wants more arguments, but also no need to.
[1] In Python 2.*
you can actually give __getitem__
an auto-unpacking signature which will raise ValueError
or TypeError
when you're indexing with too many or too few indices...:
>>> class X(object):
... def __getitem__(self, (x, y)): return x, y
...
>>> x = X()
>>> x[23, 45]
(23, 45)
Whether that's "a good way" is moot... it's been deprecated in Python 3 so you can infer that Guido didn't consider it good upon long reflection;-). Doing your own unpacking (of a single argument in the signature) is no big deal and lets you provide clearer errors (and uniform ones, rather than ones of different types for the very similar error of indexing such an instance with 1 vs, say, 3 indices;-).