38

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!

2
  • 1
    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.) Commented Nov 9, 2012 at 6:23
  • 1
    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…) Commented Nov 9, 2012 at 6:27

5 Answers 5

69

To get the variable, you can do:

getattr(test, a_string)
Sign up to request clarification or add additional context in comments.

Comments

14

use getattr this way to do what you want:

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

Comments

7

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

Comments

6

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.