Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the value of variables in dir(class) [duplicate]

I'm writing a class in python that groups a bunch of similar variables together and then assembles them into a string. I'm hoping to avoid having to manually type out each variable in the generateString method, so I want to use something like:

for variable in dir(class):
    if variable[:1] == '_':
        recordString += variable

But currently it just returns a string that has all of the variable names. Is there a way to get at the value of the variable?

like image 478
Morgan Thrapp Avatar asked Sep 15 '25 02:09

Morgan Thrapp


1 Answers

You can use the getattr() function to dynamically access attributes:

recordString += getattr(classobj, variable)

However, you probably do not want to use dir() here. dir() provides you with a list of attributes on the instance, class and base classes, while you appear to want to find only attributes found directly on the object.

You can use the vars() function instead, which returns a dictionary, letting you use items() to get both name and value:

for variable, value in vars(classobj).items():
    if variable[:1] == '_':
        recordString += value
like image 150
Martijn Pieters Avatar answered Sep 17 '25 17:09

Martijn Pieters