Access list items using getattr / setattr in Python

An attempt to access / assign items in a list with getattr and setattr functions in Python. Unfortunately, there seems to be no way to pass a place in the list index along with the list name.
Here are some of my attempts with some sample code:

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\]') 

Also note that in the second argument to the attr functions, you cannot concatenate a string and an integer in this function.

Greetings

+7
source share
4 answers
 getattr(Ls, 'thelist')[0] = 2 getattr(Ls, 'thelist').append(3) print getattr(Ls, 'thelist')[0] 

If you want to do something like getattr(Ls, 'thelist[0]') , you need to override __getattr__ or use the built-in eval .

+7
source

You can do:

 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') provides a link to the same list that can be accessed using Ls.thelist .

+4
source

As you discovered, __getattr__ does not work this way. If you really want to use list indexing, use __getitem__ and __setitem__ , and forget about getattr() and setattr() . Something like that:

 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] 
+1
source

Python is not Java. It is not recommended to use the setattr () and getattr () functions in python.

-5
source

All Articles