9

尝试在 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 函数的第二个参数中,您不能在此函数中连接字符串和整数。

干杯

4

3 回答 3

9
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]

如果您希望能够执行类似的操作getattr(Ls, 'thelist[0]'),则必须覆盖__getattr__或使用内置eval函数。

于 2011-08-01T04:44:50.357 回答
5

你可以这样做:

l = getattr(Ls, 'thelist')
l[0] = 2  # for example
l.append("bar")
l is getattr(Ls, 'thelist')  # True
# so, no need to setattr, Ls.thelist is l and will thus be changed by ops on l

getattr(Ls, 'thelist')为您提供对可以使用 访问的同一列表的引用Ls.thelist

于 2011-08-01T03:14:33.013 回答
3

正如您所发现的那样,__getattr__这种方式行不通。如果您真的想使用列表索引,请使用__getitem__and __setitem__,然后忘记getattr()and setattr()。像这样的东西:

class Lists (object):

    def __init__(self):
        self.thelist = [0,0,0]

    def __getitem__(self, index):
        return self.thelist[index]

    def __setitem__(self, index, value):
        self.thelist[index] = value

    def __repr__(self):
        return repr(self.thelist)

Ls = Lists()
print Ls
print Ls[1]
Ls[2] = 9
print Ls
print Ls[2]
于 2011-08-19T01:04:15.280 回答