how to access the class variable by string in Python?
Question:
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!
Answers:
To get the variable, you can do:
getattr(test, a_string)
use getattr this way to do what you want:
test = Test()
a_string = "b"
print getattr(test, a_string)
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"]
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.
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"]
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!
To get the variable, you can do:
getattr(test, a_string)
use getattr this way to do what you want:
test = Test()
a_string = "b"
print getattr(test, a_string)
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"]
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.
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"]