Trying to access/assign items in a list with getattr and setattr funcions in Python.
Unfortunately there seems to be no way of passing the place in the list index along with the list name.
Here's some of my tries with some example 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 in the second argument of the attr functions you can't concatenate a string and an integer in this function.
Cheers
Python setattr() Function The setattr() function sets the value of the specified attribute of the specified object.
Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.
Python setattr() function is used to assign a new value to the attribute of an object/instance. Setattr in python sets a new specified value argument to the specified attribute name of a class/function's defined object.
The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.
getattr(Ls, 'thelist')[0] = 2
getattr(Ls, 'thelist').append(3)
print getattr(Ls, 'thelist')[0]
If you want to be able to do something like getattr(Ls, 'thelist[0]')
, you have to override __getattr__
or use built-in eval
function.
You could 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')
gives you a reference to the same list that can be accessed with Ls.thelist
.
As you discovered, __getattr__
doesn't work this way. If you really want to use list indexing, use __getitem__
and __setitem__
, and forget about getattr()
and setattr()
. Something like this:
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With