我最近从ruby转移到python,在ruby中你可以创建self [nth]方法,我将如何在python中执行此操作?
换句话说,你可以做到这一点
a = myclass.new
n = 0
a[n] = 'foo'
p a[n] >> 'foo'
Run Code Online (Sandbox Code Playgroud)
欢迎光临;-)
看起来像你的意思__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]
Run Code Online (Sandbox Code Playgroud)
更新(以下评论):
如果你想使用元组作为你的密钥,你可以考虑使用一个dict内置所有这些功能的,即:
>>> a = {}
>>> n = 0, 1, 2
>>> a[n] = 'foo'
>>> print a[n]
foo
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
443 次 |
| 最近记录: |