Python类[]函数是什么意思?

3

我最近从Ruby转到Python,Ruby中你可以创建self[nth]方法,在Python中该如何实现呢?

换句话说,你可以这样做:

a = myclass.new
n = 0
a[n] = 'foo'
p a[n]  >> 'foo'

3
您能描述一下在 Ruby 中 self[nth] 的含义吗? - nmichaels
2个回答

6

欢迎来到光明面 ;-)

看起来你是指 __getitem__(self, key)__setitem__(self, key, value)

尝试:

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]

更新(根据评论):

如果您希望使用元组作为键,则可以考虑使用dict,它具有所有这些功能,即:

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

1
这个方法能够允许多维度吗?例如 i[0][3][2]。 - Ryex
2
只要 i[0]i[0][3] 返回的对象实现了 __getitem__()(用于获取)和 __setitem__()(用于设置),就可以这样做。 - johnsyweb
1
如果调用 i[0, 1, 2],key 是否会成为一个管? - Ryex
2
在这种情况下,(0, 1, 2)作为元组将是键,是的。您还可以考虑此时使用dict:a = {}; a[n] ='foo'; print a[n]; - johnsyweb
1
值得一提的是,您可以将切片传递给__getitem__,所以i[1:3:5]slice(1, 3, 5)作为key传递进去。 - Matthew Trevor

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接