Han*_*Sun 11 python variables class
代码是这样的:
class Test:
a = 1
def __init__(self):
self.b=2
Run Code Online (Sandbox Code Playgroud)
当我创建一个实例时Test,我可以b像这样访问它的实例变量(使用字符串"b"):
test = Test()
a_string = "b"
print test.__dict__[a_string]
Run Code Online (Sandbox Code Playgroud)
但它不起作用,a因为self.__dict__不包含名为的键a.那么a如果我只有一个字符串,我怎么才能访问a?
谢谢!
以这种方式使用getattr来做你想要的:
test = Test()
a_string = "b"
print getattr(test, a_string)
Run Code Online (Sandbox Code Playgroud)
试试这个:
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"]
Run Code Online (Sandbox Code Playgroud)