gpt4 book ai didi

python类[]函数

转载 作者:太空宇宙 更新时间:2023-11-03 13:05:35 25 4
gpt4 key购买 nike

我最近从 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,它内置了所有这些功能,viz:

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

关于python类[]函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3680981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com