Note that there are some explanatory texts on larger screens.

plurals
  1. POUse a dict to access nested instances of classes in Python
    primarykey
    data
    text
    <p>I'm trying to define an attribute in a nested class and then access it later using a string or maybe a list of strings. Here's code for what I'm trying to do</p> <pre><code>class MyNestedClass(object): def __init__(self): self.att1 = 5. class MyClass(object): def __init__(self): self.my_nested_inst = MyNestedClass() my_inst = MyClass() </code></pre> <p>I want to change the value of <code>my_inst.my_nested_inst.att1</code> when all I have is a list like this: <code>my_list = ['my_inst','my_nested_inst','att1']</code>. </p> <p>If I use this:</p> <pre><code>vars(vars(vars()[my_list[0]])[my_list[1]])[my_list[2]] </code></pre> <p>This works, but the problem is that I need to extend it to an arbitrary depth of nested instances. I can't figure out a good way to make this work with a for loop. Any help is greatly appreciated. </p> <p>Also, note that converting a string to a variable name in the global namespace has been well addressed, but none of the answers seem to apply here. </p> <p>EDIT1: I'll try to explain why I'm doing this, and let me know if I do a poor job of explaining. I am using scipy.optimize.fmin, and I have been using only 4 parameters for optimzation. However, I now want to expand my optimization code to handle an arbitrary number of parameters, some of which are nested attributes several layers into the class/instance hierarchy. I want to be able to create a list or dictionary at the top level to tell fmin how to unpack the parameter array for setting the nested attributes. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload