-1

another dynamic variable question, but different from other seen imho.

class MyClass:
    myvarA="alfa"
    myvarB="beta"
    myvarC="gamma"

myobj=MyClass()
for var in ["A", "B", "C"]:
    print("{}\n".format("myobj.myvar{}".format(var)))

My goal: print all attributes values in oneline using format myvar+variable as var name.

print in last line, prints "myobj.myvarA..B..C" instead of values

many thanks

backit
  • 42
  • 8
  • why do you want to do that? – balderman Mar 24 '21 at 12:41
  • because i have a many attr with similar name like example and per each attr i have to do some actions, so i don't want to copy paste each action but calls all attrs with similar name – backit Mar 24 '21 at 14:58

1 Answers1

4

You generally don't want to do that, you'll want to use a dict if you need "dynamic variable names".

Anyway, you can do this with getattr():

class MyClass:
    myvarA = "alfa"
    myvarB = "beta"
    myvarC = "gamma"


myobj = MyClass()
for var in ["A", "B", "C"]:
    var_name = f"myvar{var}"
    print(getattr(myobj, var_name))
AKX
  • 152,115
  • 15
  • 115
  • 172
  • I've seen replies to similar question with dict answer, but everyone build a dict with k,v that' is not what i need, i need cycle througn attrs without specify myvarA myvarB myvarC but myvar{variable_part} – backit Mar 24 '21 at 14:46
  • Quoting your other comment, "i have a many attr with similar name like example" and you'd need to iterate over them – you do really need a dict, not many attributes. – AKX Mar 24 '21 at 15:04
  • I've seen many times, about question similar to this, things like "You generally don't want to do that", ok please @AKX why? For OOP? change all attrs to dict could be a lot of work, and involve many parts of the program, worth a wile? – backit Mar 25 '21 at 10:14
  • 1
    It's a philosophical difference – attributes are "meant" to be more concrete and well-defined than a dict which is a "bag" of keys and values associated with them. If you need "dynamic fields", that generally means you'd want a dict. As an aside, slotsless objects are internally backed by dicts (see the `__dict__` attribute of instances)... – AKX Mar 25 '21 at 10:22