【发布时间】:2021-12-08 16:43:00
【问题描述】:
我已经定义了一个对象,我希望能够在循环中调用该对象的属性,但我不确定如何执行此操作。这是我写的(错误的)示例代码,试图表明我想做什么:
class my_data:
def __init__(self,a,b,c,d):
self.a = 'e'
self.b = 'f'
self.c = 'g'
self.d = 'h'
test=my_data('a','b','c','d')
#print(test.a)
#e
index=['a','b','c','d']
#what I want:
my_var = test.index[2]
#where index[2] is equivalent to c and thus my_var is 'g'
我得到的错误是:
AttributeError: 'my_data' object has no attribute 'index'
我明白,因为它正在寻找特定的属性索引而不是数组索引[2] 的值,但我不知道如何解决这个问题。我需要它,因为我想循环使用它。
谢谢!
【问题讨论】:
-
my_data是一个类,类不是一个列表。即使它是一个列表,它也不起作用,因为您使用方括号[]而不是括号()用于index函数 -
您根本没有存储数组,因此类似索引的访问将不起作用。
my_data实例中的唯一项目是a、b、c和d。您可以通过test.a、test.b、...访问它们 -
另外,请参阅this 进行迭代。
标签: python class object attributes