【问题标题】:Python: get attribute from class objects stored in an arrayPython:从存储在数组中的类对象中获取属性
【发布时间】:2020-11-05 13:52:43
【问题描述】:

我想获取包含在 ndarray 中的每个对象的属性。考虑下面的代码,在向量化之后,函数返回一个带有对象的 ndarray。从数组中的每个对象中,我想获取属性并将属性存储在一个新数组中。

类和函数是更复杂的类和函数的虚拟对象。我知道从stud = new_student(["Michael","Rachel"], [1,2]); stud.name 可以得到一个包含名称的列表,但是这对于我使用的函数而不是new_student 是不可能的。

import numpy as np

class Student: 
      
    # class variable 
    stream = "COE"
      
    # Constructor 
    def __init__(self, name, roll_no): 
          
        self.name = name 
        self.roll_no = roll_no 
        
def new_student(name, roll_no):
    return Student(name, roll_no)

new_student_vec = np.vectorize(new_student)

studArr = new_student_vec(["Michael","Rachel"], [1,2])

studArr.name

【问题讨论】:

标签: python numpy class


【解决方案1】:
In [3]: class Student:
   ...: 
   ...:     # class variable 
   ...:     stream = "COE"
   ...: 
   ...:     # Constructor 
   ...:     def __init__(self, name, roll_no):
   ...: 
   ...:         self.name = name
   ...:         self.roll_no = roll_no
   ...:     def __repr__(self):
   ...:         return f'Student <{self.name}, {self.roll_no}>'
   ...: 
   ...: 
   ...: def new_student(name, roll_no):
   ...:     return Student(name, roll_no)
   ...: 
   ...: new_student_vec = np.vectorize(new_student)
   ...: 
   ...: studArr = new_student_vec(["Michael","Rachel"], [1,2])
   ...: 

添加 repr 后,数组现在会打印:

In [4]: studArr
Out[4]: array([Student <Michael, 1>, Student <Rachel, 2>], dtype=object)

当您尝试name 时,您会得到:

In [5]: studArr.name
Traceback (most recent call last):
  File "<ipython-input-5-9248234e8082>", line 1, in <module>
    studArr.name
AttributeError: 'numpy.ndarray' object has no attribute 'name'

您确实应该显示此错误。你明白发生了什么吗?仅仅因为数组中的对象具有该属性,并不意味着数组本身具有它。

考虑相同对象的列表。询问列表中的name 也没有任何意义。

In [6]: alist = studArr.tolist()
In [7]: alist
Out[7]: [Student <Michael, 1>, Student <Rachel, 2>]
In [8]: alist.name
Traceback (most recent call last):
  File "<ipython-input-8-f77eb3c13383>", line 1, in <module>
    alist.name
AttributeError: 'list' object has no attribute 'name'

您仍然需要向每个元素询问该属性:

In [9]: [s.name for s in alist]
Out[9]: ['Michael', 'Rachel']

您可以像使用构造函数一样使用np.vectorize 来获取属性(或np.frompyfunc),但结果和时间基本相同。使用对象数组而不是列表几乎没有优势。

理想化“矢量化”仅适用于数字 dtype。快速编译的代码是用c 编写的,使用c 数字类型,如浮点数和双精度数。对象 dtype 需要以与列表相同的方式引用 Python 对象。

【讨论】:

    【解决方案2】:

    您可以为此使用列表推导

    names = [s.name for s in studArr]
    print(names)
    

    输出

    ['Michael', 'Rachel']
    

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2022-10-19
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      相关资源
      最近更新 更多