开发者

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'


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


You use __getitem__.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜