Доступ к элементам списка с помощью getattr / setattr в Python

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

Ура

7
задан insomniaccanuck 1 August 2011 в 03:10
поделиться