python - 迭代类属性

标签 python python-3.x

我有一个类 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/

相关文章:

python - 使用python shelve跨平台

python - 将带有项目列表的字典转换为 Pandas 数据框

python - 使用 Dask 根据列值保存多个 csv 文件

python - 从 Python 2.x 中调用 Python 3.x 程序的最佳方法是什么?

python-3.x - Julia 的 reshape

python - 设置日期时间字符串 : Python 中的毫秒精度

python - absl.flags 错误 : Trying to access flag before flags were parsed

python - 尝试在 Python 3 中将时间转换为整数

python - 使用 pyodbc 连接到 MS Access

python-3.x - AWS Patch Manager 在 Ubuntu 22.04 上失败