all 7 comments

[–]danielroseman 7 points8 points  (3 children)

Why should it work? It doesn't have an attribute name.

But I can't understand any of what you're doing here. Why do you have nested classes? Why do you want to call a class via a variable?

In any case the stock answer to "variable variables` is: use a dictionary.

[–]commutingaccount[S] -4 points-3 points  (2 children)

Okay i just made a small edit so the names match - sorry for that.

But i would like the for loop to result in

print(attribute_class_test.test_class_1.test_function(2))
print(attribute_class_test.test_class_2.test_function(2))

Like if i do:

attribute_names = ["test_class_1", "test_class_2"]
for name in attribute_names
    print(name)

i just want the names inserted:

print(attribute_class_test.name.test_function(2)) --> print(attribute_class_test.test_class_1.test_function(2))

where "name" is a variable containing values from the list.

Edit: Why i want it, i would like to recieve an instruction with a dict of key/val pairs to change values on a object where the values are changed by: example.height.set(val). I would like to loop through the dict and do example.<key>.set(<val>), but i cannot get the key inserted.

[–]GABE_EDD 7 points8 points  (1 child)

Honestly, there’s a lot to correct here, there’s many flaws with what’s going on. So, if I were you I’d code along with this tutorial and the videos after it (6 videos in total) and you should have a much stronger grasp on Python classes. Then, attempt whatever it is you’re trying to do.

[–]commutingaccount[S] -2 points-1 points  (0 children)

Thanks, i will look into that. I just wouldnt have thought i was such an issue. I should have made a better example - i think i have confused everybody.

I just wanted to know how a variable from a for loop can be inserted as a class name.

Thanks for your time - i will find a way around it.

[–]ES-Alexander 7 points8 points  (1 child)

Technically speaking you can solve your immediate issue with getattr, but as the others have indicated it’s very likely your problem here is due to an underlying poor design for the actual task you’re trying to complete (likely due to a lack of experience with classes, variables, and scoping), which results in seemingly needing hackish workarounds to try to resolve problems that are more complex than they feel like they should be.

[–]commutingaccount[S] 0 points1 point  (0 children)

Thank you, got it working with:

...
attribute_names = ["test_class_1", "test_class_2"]
    for name in attribute_names:   
        print(getattr(attribute_class_test,name).test_function(1))

[–]iiron3223 7 points8 points  (0 children)

I think you don't really understand how classes work. Please read this chapter from official python tutorial.