3

I recently moved from ruby to python and in ruby you could create self[nth] methods how would i do this in python?

in other words you could do this

a = myclass.new
n = 0
a[n] = 'foo'
p a[n]  >> 'foo'
1
  • 3
    Can you describe what self[nth] meant in Ruby? Commented Sep 9, 2010 at 22:24

2 Answers 2

6

Welcome to the light side ;-)

It looks like you mean __getitem__(self, key). and __setitem__(self, key, value).

Try:

class my_class(object):

    def __getitem__(self, key):
        return some_value_based_upon(key) #You decide the implementation here!

    def __setitem__(self, key, value):
        return store_based_upon(key, value) #You decide the implementation here!


i = my_class()
i[69] = 'foo'
print i[69]

Update (following comments):

If you wish to use tuples as your key, you may consider using a dict, which has all this functionality inbuilt, viz:

>>> a = {}
>>> n = 0, 1, 2
>>> a[n] = 'foo'
>>> print a[n]
foo
Sign up to request clarification or add additional context in comments.

5 Comments

could this method allow for multiple dimensions? ie. i[0][3][2]
Provided that the objects returned by i[0] and i[0][3] implement __getitem__() [for getting] and __setitem__() [for setting], yes.
if i[0, 1, 2] was called would key be a tube?
In this case, (0, 1, 2) as a tuple would be the key, yes. You may also consider using a dict at this point: a = {}; a[n] = 'foo'; print a[n];
It's also worth pointing out that you can pass slices to __getitem__, so i[1:3:5] would pass slice(1, 3, 5) in as the key.
2

You use __getitem__.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.