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.

3
  • You can also use getattr() as suggested in this question Commented Jan 21, 2022 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 Commented Jan 21, 2022 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) Commented Jan 21, 2022 at 22:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Wouldn't dot dict get similar results? bot.__dict__?
@ybressler_simon: In this case, "yes". vars() is more generic and works with objects other than class instances. Also in this case it's less typing and better conveys the intent IMO.
fair! will look for use cases in my curr work for vars() :)
@ybressler_simon: Also note that there are other things in __dict__ besides the attributes (which you will have to skip or filter-out some way).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.