1

Is it possible to do something like this?

class child:
    def __init__(self):
        self.figure = "Square"
        self.color = "Green"

bot = child()
bot_parameters = ['color', 'figure'] 

[print(bot.i) for i in bot_parameters] #Attribute Error from the print function.

I know I can access the parameter values with __dict__ but I wanted to know if it is possible to concatenate the parameters to programmatically/dynamically get the values.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • You can also use `getattr()` as suggested in this [question](https://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it) – quamrana Jan 21 '22 at 21:03
  • it is unclear what you expect to achieve. What should be the value for `size` which is indeed not defined? It's unclear what you mean by _concatenate the parameters to programatically/Dynamically get the values_ – buran Jan 21 '22 at 21:08
  • for example i can write the code: print(bot.figure) print(bot.color) But my question is if its possible to do something like: for parameter in ['figure', 'color']: print(bot.parameter) – Aldhair Garza Jan 21 '22 at 22:11

1 Answers1

2

You can use the built-in vars() and getattr() functions together and retrieve the class instance's attributes dynamically like this:

class Child:
    def __init__(self):
        self.figure = "Square"
        self.color = "Green"

bot = Child()

print([getattr(bot, attrname) for attrname in vars(bot)])  # -> ['Square', 'Green']

You could also just hardcode ['figure', 'color'], but that's not as "dynamic" and would have to be updated whenever the class' attributes were changed.

martineau
  • 119,623
  • 25
  • 170
  • 301