Home > Mobile >  Programmatically / Dynamically concatenate parameters to an object to access data
Programmatically / Dynamically concatenate parameters to an object to access data

Time:01-24

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.

CodePudding user response:

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.

  •  Tags:  
  • Related