我有这样一个类:
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,它只适用于函数(从我可以告诉)以及有用户扩展字典和使用自我。__getitem__,但这也不工作。最好的方法是什么?
稍微扩展一下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]
然而,我个人不认为这是一个很好的风格- getattr将允许你访问实例的任何属性,包括像doSomething方法本身,甚至实例的__dict__。我建议你实现一个数据源字典,像这样:
class User:
def __init__(self):
self.data_sources = {
"data": [1,2,3],
"other_data":[4,5,6],
}
def doSomething(self, source):
dataSource = self.data_sources[source]
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
又产生:
[1,2,3]
[4,5,6]
稍微扩展一下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]
然而,我个人不认为这是一个很好的风格- getattr将允许你访问实例的任何属性,包括像doSomething方法本身,甚至实例的__dict__。我建议你实现一个数据源字典,像这样:
class User:
def __init__(self):
self.data_sources = {
"data": [1,2,3],
"other_data":[4,5,6],
}
def doSomething(self, source):
dataSource = self.data_sources[source]
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
又产生:
[1,2,3]
[4,5,6]