2012-11-09 95 views
8

的代码是这样的:如何通过Python中的字符串访问类变量?

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

谢谢!

+0

“self .__ dict__”不包含名为“a”的键的原因是它在'self .__ class __.__ dict__'中。如果你真的想手动操作,你可以阅读搜索顺序中的属性,并按照相同的顺序检查所有内容......但你真的不想手动执行操作。 (你必须处理插槽,属性,经典与新风格的类,自定义__dict__,自定义描述符以及各种其他有趣的东西,但与解决问题无关。 ) – abarnert

+1

PS,因为这很明显是Python 2.x,所以在这里你可能想要'class Test(object)',除非你有特定的原因来避免新风格​​的类。即使是简单的小测试程序,也值得养成这种习惯。 (特别是对于那些明确依赖于两类不同类型的测试程序......) – abarnert

回答

21
getattr(test, a_string) 

加上一些更多的字符,所以我可以发布它。

9

使用getattr这样做你想要什么:

test = Test() 
a_string = "b" 
print getattr(test, a_string) 
4

试试这个:

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"] 
1

您可以使用:

getattr(Test, a_string, default_value)

与第三个参数返回如果a_string不是default_value发现在Test类。

相关问题