How to access class variable line by line in Python?

Codes are as follows:

class Test: a = 1 def __init__(self): self.b=2 

When I make an instance of Test , I can access its instance variable b , like this (using the string "b"):

 test = Test() a_string = "b" print test.__dict__[a_string] 

But this does not work for a , since self.__dict__ does not contain a key named a . Then how can I access a if I only have string a ?

Thanks!

+8
variables python class
source share
4 answers
 getattr(test, a_string) 

plus a few characters, so I can post it.

+21
source share

use getattr this way to do what you want:

 test = Test() a_string = "b" print getattr(test, a_string) 
+9
source share

Try the following:

 class Test: a = 1 def __init__(self): self.b=2 test = Test() a_string = "b" print test.__dict__[a_string] print test.__class__.__dict__["a"] 
+4
source share

You can use:

getattr(Test, a_string, default_value)

with the third argument to return some default_value if a_string not found in the Test class.

+1
source share

All Articles