Python:从字符串访问类属性[重复]
- 2025-01-21 09:01:00
- admin 原创
- 68
问题描述:
我有如下课程:
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
extenddict
和 using 的self.__getitem__
方法,但这些都不起作用。最好的方法是什么?
解决方案 1:
x = getattr(self, source)
`source如果命名自身的任何属性,包括您示例中的,都将完美地工作
other_data`。
解决方案 2:
一张图片胜过千言万语:
>>> class c:
pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
解决方案 3:
getattr(x, 'y')
相当于x.y
setattr(x, 'y', v)
相当于x.y = v
delattr(x, 'y')
相当于del x.y
解决方案 4:
稍微扩展一下亚历克斯的回答:
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]
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD