代码是这样的:
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)
关于python - 如何在 Python 中通过字符串访问类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13303100/