In python3 I have the following complete code:
class Test:
def __init__(self):
self.x = [42, 4711]
self.y = [4, 6]
self.z = 99
t = Test()
v = 'x[1]' # or can be 'y[0]' or can be 'z' ...
print(eval('t.'+v))
print(getattr(t,v))
which throws an error for the last line
AttributeError: 'Test' object has no attribute 'x[1]'
Is there a way to access a list inside an object via getattr
, or do I have to use eval
in this case?
HINT: The index is part of the string! I do not know if the attribute I am about to access is a list or just a value, This need to work for the following cases:
v = 'x[0]'
v = 'x[1]'
v = 'y[0]'
v = 'z'