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"]
Related videos on Youtube
Comments
-
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 variableb
like this(using the string "b"):test = Test() a_string = "b" print test.__dict__[a_string]
But it doesn't work for
a
asself.__dict__
doesn't contain a key nameda
. Then how can I accessa
if I only have a stringa
?Thanks!
-
abarnert over 11 yearsThe reason
self.__dict__
doesn't contain a key nameda
is 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.) -
abarnert over 11 yearsPS, 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…)
-