how to access the class variable by string in Python?

27,530

Solution 1

To get the variable, you can do:

getattr(test, a_string)

Solution 2

use getattr this way to do what you want:

test = Test()
a_string = "b"
print getattr(test, a_string)

Solution 3

Try this:

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"]

Solution 4

You can use:

getattr(Test, a_string, default_value)

with a third argument to return some default_value in case a_string is not found on Test class.

Solution 5

Since the variable is a class variable one can use the below code:-

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

print Test.__dict__["a"]
Share:
27,530

Related videos on Youtube

Hanfei Sun
Author by

Hanfei Sun

Just another stackoverflow user cs.cmu.edu/~hanfeis

Updated on June 29, 2020

Comments

  • Hanfei Sun
    Hanfei Sun almost 4 years

    The codes are like this:

    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 it doesn't work for a as self.__dict__ doesn't contain a key named a. Then how can I accessa if I only have a string a?

    Thanks!

    • abarnert
      abarnert over 11 years
      The reason self.__dict__ doesn't contain a key named a is that it's in self.__class__.__dict__. If you really want to do things manually, you can read up on the search order for attributes and check everything in the same order… but you really don't want to do things manually. (You'd have to deal with slots, properties, classic vs. new-style classes, custom __dict__s, custom descriptors, and all kinds of other stuff that's fun to learn about, but not directly relevant to solving your problem.)
    • abarnert
      abarnert over 11 years
      PS, since this is clearly Python 2.x, you probably want class Test(object) here, unless you have a specific reason to avoid new-style classes. Even for simple little test programs, it's worth getting into the habit. (And especially for test programs that explicitly rely on ways in which the two kinds of classes differ…)