4

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?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67

1 Answers1

8

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • This looks much better than what I have. The only problem is that I'm getting a Runtime Error saying that the size of the dictionary is changing during iteration. – Morgan Thrapp Oct 29 '14 at 15:31
  • @mpthrapp: are you altering attributes on the class itself? You can get a copy of the items first (with `list()`). – Martijn Pieters Oct 29 '14 at 15:38