【问题标题】:Accessing list items with getattr/setattr in Python在 Python 中使用 getattr/setattr 访问列表项
【发布时间】:2011-10-17 03:50:46
【问题描述】:

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

干杯

【问题讨论】:

  • @BrainStorm 的回答是正确的,但这通常带有“你的做法错误”的味道。你到底想完成什么?
  • 这到底是什么……?列表中的项目不是列表的属性,所以这显然行不通。
  • 真正想做什么?
  • @insomniaccanuck 我们知道您在这种情况下要尝试做什么,但是您正在尝试解决一个更大的问题,促使您尝试这些。也许您是trying to parse a hierarchical query string into nested objects/lists 或者您想要一个配置项,它可以让您从配置项中唯一地遍历嵌套对象层次结构,或者您可能正在尝试做其他事情,但是有关更大图景的更多信息将帮助我们指导您解决方案。
  • 好的,更多的阅读和思考我认为最好的方法是使用带有嵌套列表的字典。函数 setattr 没有我需要的功能(可能有充分的理由)。我试图做的是建立一个 n 维集合来处理一个排列组。我来自组合学背景;还没有那么多 CS 术语。学习python(和编码)来尝试找工作。谢谢大家

标签: python getattr setattr


【解决方案1】:
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]

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

【讨论】:

  • 这就是一半。谢谢。以为我已经为 setattr 和 getattr 尝试过,但我想我只尝试过 setattr。它为 setattr 产生此错误: setattr(Ls, 'thelist', 3)[2] TypeError: 'NoneType' object is not subscriptable
  • getattr(Ls, 'thelist') 返回thelistattribute,这是一个列表。随心所欲地处理返回的结果。 'NoneType' object is not subscriptable 这意味着当您调用此thelist 时为无,何时应为[](列表)。先初始化一下。
  • 阅读更多关于列表的信息 - diveintopython.org/native_data_types/lists.html。看起来你很累,错过了一些清晰的东西。
【解决方案2】:

你可以这样做:

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 访问的同一列表的引用。

【讨论】:

  • 感谢这个可行的解决方法,但它不能很好地扩展。那就是你必须重新分配整个列表。试图从列表中分配/调用一项。
  • 没有必要做setattr(Ls, 'thelist',l)。 Ls.thelist 和和 l 是 same 列表,因此在这种情况下设置 l[0] 等效于 Ls.thelist[0]=2
  • 最终结果是一样的,但 BrainStorm 的方法允许您通过字符串数据进行分配。您的是直接按名称分配的,不能解决我的问题。
  • Ls.thelist is getattr(Ls, 'thelist') 所以,是的,不需要setattr 行。我想我会编辑删除。
【解决方案3】:

正如您所发现的,__getattr__ 不能以这种方式工作。如果你真的想使用列表索引,使用__getitem____setitem__,忘记getattr()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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多