尝试使用Python中的getattr和setattr函数访问/分配列表中的项目。
不幸的是,似乎没有办法将列表索引中的位置与列表名称一起传递。
这是我的一些示例代码的尝试:
class Lists (object):
def __init__(self):
self.thelist = [0,0,0]
Ls = Lists()
# trying this only gives 't' as the second argument. Python error results.
# Interesting that you can slice a string to in the getattr/setattr functions
# Here one could access 'thelist' with with [0:7]
print getattr(Ls, 'thelist'[0])
# tried these two as well to no avail.
# No error message ensues but the list isn't altered.
# Instead a new variable is created Ls.'' - printed them out to show they now exist.
setattr(Lists, 'thelist[0]', 3)
setattr(Lists, 'thelist\[0\]', 3)
print Ls.thelist
print getattr(Ls, 'thelist[0]')
print getattr(Ls, 'thelist\[0\]')
还要注意,在attr函数的第二个参数中,您不能在此函数中连接字符串和整数。
干杯
最佳答案
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]
如果您希望能够执行类似
getattr(Ls, 'thelist[0]')
的操作,则必须覆盖 __getattr__
或使用内置的 eval
函数。