This question already has answers here:
How to access object attribute given string corresponding to name of that attribute
(2个答案)
去年关闭。
我希望能够通过其名称选择类的属性。这是我的代码:
我怎样才能做到这一点?
工作示例:
(2个答案)
去年关闭。
我希望能够通过其名称选择类的属性。这是我的代码:
class example(object):
def __init__(self):
self.one = "1"
self.two = "2"
x = example()
list = ["one", "two"]
# I want to get x.one here by referring to it by list[0]
我怎样才能做到这一点?
工作示例:
class example(object):
def __init__(self):
self.one = "one"
self.two = "two"
def test(self):
list = ["one", "two"]
print(getattr(self, list[1]))
x = example()
x.test()
最佳答案
如果您尝试按对象名称访问对象属性,请尝试以下操作:
list = ['one', 'two']
print getattr(x, list[1])
关于python - 如何从列表中调用Python类实例? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50031264/
10-12 16:56