类属性的迭代



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

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将包含要访问的属性的子集。

最新更新