Доступ к элементам списка с помощью getattr / setattr в Python - PullRequest
7 голосов
/ 01 августа 2011

Попытка получить доступ / назначить элементы в списке с помощью функций getattr и setattr в Python.К сожалению, кажется, нет способа передать место в индексе списка вместе с именем списка.
Вот некоторые из моих попыток с примером кода:

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, вы не можете объединить строку и целое число в этой функции.

Cheers

Ответы [ 3 ]

7 голосов
/ 01 августа 2011
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]

Если вы хотите сделать что-то вроде getattr(Ls, 'thelist[0]'), вам нужно переопределить __getattr__ или использовать встроенную функцию eval.

4 голосов
/ 01 августа 2011

Вы можете сделать:

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.

2 голосов
/ 19 августа 2011

Как вы обнаружили, __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]
...