gpt4 book ai didi

python - 迭代类属性

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:25 25 4
gpt4 key购买 nike

我有一个类 abalone,具有三个属性 MIF。像这样访问它们:

abalone.M
Out[81]:
array([[ 0.455 , 0.365 , 0.095 , ..., 0.2245, 0.101 , 0.15 ],
[ 0.35 , 0.265 , 0.09 , ..., 0.0995, 0.0485, 0.07 ],
[ 0.44 , 0.365 , 0.125 , ..., 0.2155, 0.114 , 0.155 ],
...,
[ 0.59 , 0.44 , 0.135 , ..., 0.439 , 0.2145, 0.2605],
[ 0.6 , 0.475 , 0.205 , ..., 0.5255, 0.2875, 0.308 ],
[ 0.71 , 0.555 , 0.195 , ..., 0.9455, 0.3765, 0.495 ]])

效果非常好。我将如何迭代它们?我的尝试

for item in [M, I, F]:
abalone.item
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-84-c9c2187c3451> in <module>()
----> 1 for item in [M, I, F]:
2 abalone.item

NameError: name 'M' is not defined

不幸的是,不起作用。

编辑:尝试

for item in ['M', 'I', 'F']:
abalone.item
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-86-b9d61335686f> in <module>()
1 for item in ['M', 'I', 'F']:
----> 2 abalone.item

AttributeError: 'Abalone' object has no attribute 'item'

也不起作用。

最佳答案

试试这个:

for attr, value in abalone.__dict__.items():
print attr,value

如果不起作用,请告诉我。

编辑(根据问题的变化):

l = ['M','I','F']
for attr, value in x.__dict__.iteritems():
if attr in l:
print attr,value

此处 l 将包含您要访问的属性子集。

关于python - 迭代类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853932/

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