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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With