Python:从字符串访问类属性

Python:从字符串访问类属性,python,syntax,Python,Syntax,我的课程如下: class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data 我想在doSomething中为源变量传递一个字符串,并访问同名的类成员 我试过getattr,它只对

我的课程如下:

class User:
    def __init__(self):
        self.data = []
        self.other_data = []

    def doSomething(self, source):
        // if source = 'other_data' how to access self.other_data
我想在
doSomething
中为源变量传递一个字符串,并访问同名的类成员


我试过
getattr
,它只对函数起作用(据我所知),也试过让
User
extend
dict
并使用
self.\uu getitem\uuuu
,但这也不起作用。最好的方法是什么?

x=getattr(self,source)
如果
source
命名self的任何属性,包括示例中的
其他_数据

稍微扩展Alex的答案:

class User:
    def __init__(self):
        self.data = [1,2,3]
        self.other_data = [4,5,6]
    def doSomething(self, source):
        dataSource = getattr(self,source)
        return dataSource

A = User()
print A.doSomething("data")
print A.doSomething("other_data")
将产生: [1, 2, 3] [4, 5, 6] 再次: [1, 2, 3] [4, 5, 6] [1, 2, 3] [4, 5, 6]
一幅画抵得上千言万语:

>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
  • getattr(x,'y')
    相当于
    x.y
  • setattr(x,'y',v)
    相当于
    x.y=v
  • delattr(x,'y')
    相当于
    del x.y

我没有正确解释。。。我道歉。我可以通过字符串获取数据。但是,我在使用上述方法设置数据时遇到问题。具体地说,我已经尝试了getattr(self,“other_data”)=[1,2,3]以及self.\uu setitem_uuu(“other_data”),[1,2,3])@sberry2A,
getattr()
仅用于获取,
setattr()
用于设置。您不能从
getattr()
中为返回值赋值。我特别喜欢这个答案,因为它简单地说明了getattr()函数也在类方法之外工作(意识到这是一个旧线程)。我很困惑/总是因为口述而忘记这一点。如果我想从dict中获取一个值,我可以说:myDict.get('keyy'),因此我希望属性以同样的方式工作:myObject.getattr('attr_name')。但是相反,他们将对象作为第一个参数……好吧,但明显的不一致性是我遇到问题的原因。如何根据
v
的值字符串访问
x.y
?@user2284570:如果
v
包含字符串
'y'
,那么
getattr(x,v)
给出了
x.y
@md2perpe的值,但实际情况并非如此。@user2284570:那么您的情况如何?
>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'