Python: access class property from string
本问题已经有最佳答案,请猛点这里访问。
我有一个如下的班级:
1 2 3 4 5 6 7 | class User: def __init__(self): self.data = [] self.other_data = [] def doSomething(self, source): // if source = 'other_data' how to access self.other_data |
我想为
我试过
如果
一幅画胜过千言万语:
1 2 3 4 5 6 7 8 | >>> 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 。
稍微延长亚历克斯的回答:
1 2 3 4 5 6 7 8 9 10 11 | 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 | [1, 2, 3] [4, 5, 6] |
。
然而,我个人并不认为这是一种很好的风格——
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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 | [1, 2, 3] [4, 5, 6] |
。