Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python class [] function

Tags:

python

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'
like image 738
Ryex Avatar asked May 19 '26 06:05

Ryex


2 Answers

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
like image 70
Johnsyweb Avatar answered May 21 '26 19:05

Johnsyweb


You use __getitem__.

like image 34
Matthew Flaschen Avatar answered May 21 '26 19:05

Matthew Flaschen