我最近从Ruby转到Python,Ruby中你可以创建self[nth]方法,在Python中该如何实现呢?
换句话说,你可以这样做:
a = myclass.new
n = 0
a[n] = 'foo'
p a[n] >> 'foo'
我最近从Ruby转到Python,Ruby中你可以创建self[nth]方法,在Python中该如何实现呢?
换句话说,你可以这样做:
a = myclass.new
n = 0
a[n] = 'foo'
p a[n] >> 'foo'
欢迎来到光明面 ;-)
看起来你是指 __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
i[0]
和 i[0][3]
返回的对象实现了 __getitem__()
(用于获取)和 __setitem__()
(用于设置),就可以这样做。 - johnsywebdict
:a = {}; a[n] ='foo'; print a[n]; - johnsyweb__getitem__
,所以i[1:3:5]
将slice(1, 3, 5)
作为key传递进去。 - Matthew Trevor
self[nth]
的含义吗? - nmichaels