gpt4 book ai didi

python - 如何从列表中调用 Python 类实例?

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:22 24 4
gpt4 key购买 nike

<分区>

我希望能够通过名称选择类的属性。这是我的代码:

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()

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com