Python class function []

I recently switched from ruby ​​to python, and in ruby ​​you could create your own [nth] methods, how would this be done in python?

In other words, you could do it

a = myclass.new
n = 0
a[n] = 'foo'
p a[n]  >> 'foo'
+3
source share
2 answers

Welcome to the bright side; -)

Sounds 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 want to use tuples as your key, you can use dictone that has all this functionality, namely:

>>> a = {}
>>> n = 0, 1, 2
>>> a[n] = 'foo'
>>> print a[n]
foo
+7
source

You are using __getitem__.

+2
source

Source: https://habr.com/ru/post/1764076/


All Articles