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!
self.__dict__doesn't contain a key namedais that it's inself.__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.)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…)