代码是这样的:
class Test:
a = 1
def __init__(self):
self.b=2
当我创建一个实例时Test,我可以像这样访问它的实例变量b(使用字符串“b”):
test = Test()
a_string = "b"
print test.__dict__[a_string]
但它不适用于a不self.__dict__包含名为 的键a。a那么如果我只有一个字符串,我该如何访问a?
谢谢!
要获取变量,您可以执行以下操作:
getattr(test, a_string)
以这种方式使用getattr来做你想做的事:
test = Test()
a_string = "b"
print getattr(test, a_string)
尝试这个:
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"]
您可以使用:
getattr(Test, a_string, default_value)
使用第三个参数返回一些default_value以防万一在课堂a_string上找不到。Test
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"]