Ryex
Ryex

Reputation: 337

python class [] function

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'

Upvotes: 3

Views: 464

Answers (2)

johnsyweb
johnsyweb

Reputation: 141810

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

Upvotes: 6

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

You use __getitem__.

Upvotes: 2

Related Questions